Skip to content

Commit

Permalink
Fixed MongoModelStorage.insert()
Browse files Browse the repository at this point in the history
  • Loading branch information
colemancda committed Aug 26, 2023
1 parent fbbce91 commit eadc4f6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
11 changes: 10 additions & 1 deletion Sources/MongoDBModel/MongoDatabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
8 changes: 5 additions & 3 deletions Tests/CoreModelMongoDBTests/MongoDBModelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down

0 comments on commit eadc4f6

Please sign in to comment.