Details
-
Improvement
-
Resolution: Done
-
Unknown
-
1.8.2
-
None
-
None
-
Not Needed
Description
mongo.IsDuplicateKeyError is a convenient helper to detect duplicates. It however does not work when the duplicate key error is returned as part of a bulk. While it will tell whether any of the errors in the bulk was a duplicate, it can't be applied to the individual errors (of type BulkWriteError) within the BulkWriteException unless I missed a conversion somewhere.
_, err := collection.BulkWrite(ctx, ops, options.BulkWrite().SetOrdered(false)) |
if err != nil { |
berr := &mongo.BulkWriteException{}
|
if !errors.As(err, berr) { |
return err |
}
|
for _, we := range berr.WriteErrors { |
// >>>> |
// >>>> Does not work: |
// >>>> mongo.IsDuplicateKeyError() does not understand either 'we' (BulkWriteError) or 'we.WriteError' (WriteError) |
// >>>> |
if mongo.IsDuplicateKeyError(we) { |
continue |
}
|
return err |
}
|
// The bulk only contains duplicate key errors: all good |
}
|
It's a bit limiting since it's hard to decide what do with a whole batch just knowing that at least one of the operations failed due to a duplicate key error. Iterating on the errors in the bulk should allow mongo.IsDuplicateKeyError to be applied to them and return true if relevant. It has a code and a message so the same logic as for serverError should be applicable.