Hi all. I’m in Swift 5.8, in Xcode 14.3, on macOS 13.3.1, MacBook Pro M1 Max. Locally hosted MongoDb Community Server 6.
I have this function:
func fInsertSome(_ sCollection: String, documents: [some Codable]) throws {
let zCollection = zDb.collection(sCollection.lowercased()) // returns actual collection from collection name
let azDocuments = try documents.map { try BSONEncoder().encode($0) }
do {
try zCollection.insertMany(azDocuments)
}
catch {
if let errorCode = (error as? MongoSwift.MongoError.BulkWriteError)?.writeFailures?.first?.code, errorCode == 11000 {
// one of the documents has a duplicate key. If so, switch to writing them one by one, and handle each one individually:
for document in documents {
do {
let zDocument = try BSONEncoder().encode(document)
try zCollection.insertOne(zDocument)
}
catch {
if let errorCode = (error as? MongoSwift.MongoError.WriteError)?.writeFailure?.code, errorCode == 11000 {
}
else {
print("This error occurred when trying to insertOne: ", error)
throw error
}
}
}
}
else {
print("This error occurred when trying to insertMany: ", error)
throw error
}
}
}
I’m getting a warning on the two if let errorCode ... errorCode == 11000
lines:
“Cast from ‘any Error’ to unrelated type ‘MongoError.BulkWriteError’ always fails”
I’ve read the documentation (here) that says these two functions throws four types of errors each (including the two I’m using: MongoError.BulkWriteError, MongoError.WriteError), but it seems I’m not casting it correctly, or something…?
I’ve tried a few things, including some suggestions from ChatGPT, but neither it nor I can figure it out, so far.
Can anyone here help please?
Thanks in advance!