From eadc4f6628c768eaa0e35f63b6aa2e93ee9a843a Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Sat, 26 Aug 2023 13:44:32 -0400 Subject: [PATCH] Fixed `MongoModelStorage.insert()` --- Sources/MongoDBModel/MongoDatabase.swift | 11 ++++++++++- Tests/CoreModelMongoDBTests/MongoDBModelTests.swift | 8 +++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/Sources/MongoDBModel/MongoDatabase.swift b/Sources/MongoDBModel/MongoDatabase.swift index b1a9eeb..fc3c006 100644 --- a/Sources/MongoDBModel/MongoDatabase.swift +++ b/Sources/MongoDBModel/MongoDatabase.swift @@ -126,8 +126,17 @@ internal extension MongoDatabase { ) async throws { let entityName = value.entity let collection = self.collection(entityName, options: options) + let options: CountDocumentsOptions? = nil + let filter: BSONDocument = [ + BSONDocument.BuiltInProperty.id.rawValue: .string(value.id.rawValue) + ] + let count = try await collection.countDocuments(filter, options: options) let document = try BSONDocument(model: value) - try await collection.insertOne(document) + if count > 0 { + try await collection.findOneAndUpdate(filter: filter, update: document) + } else { + try await collection.insertOne(document) + } } func insert( diff --git a/Tests/CoreModelMongoDBTests/MongoDBModelTests.swift b/Tests/CoreModelMongoDBTests/MongoDBModelTests.swift index 4fe6653..b29ecca 100644 --- a/Tests/CoreModelMongoDBTests/MongoDBModelTests.swift +++ b/Tests/CoreModelMongoDBTests/MongoDBModelTests.swift @@ -68,14 +68,16 @@ final class MongoDBModelTests: XCTestCase { checkout: campground.officeHours ) - // set relationship - campground.units = [rentalUnit.id] - var campgroundData = try campground.encode(log: { print("Encoder:", $0) }) try await store.insert(campgroundData) let rentalUnitData = try rentalUnit.encode(log: { print("Encoder:", $0) }) XCTAssertEqual(rentalUnitData.relationships[PropertyKey(Campground.RentalUnit.CodingKeys.campground)], .toOne(ObjectID(campground.id))) try await store.insert(rentalUnitData) + + // update value + campground.units = [rentalUnit.id] + try await store.insert(campground) + campgroundData = try await store.fetch(Campground.entityName, for: ObjectID(campground.id))! campground = try .init(from: campgroundData, log: { print("Decoder:", $0) }) XCTAssertEqual(campground.units, [rentalUnit.id])