I have three unique indexes in my collection. When user accidentally insert a data having a duplicate in the field B
, how do I know that the duplication comes from field B
?
On unique index constraint violation, mongo-go-driver behavior is returning err WriteException
, which basically consist of an array of WriteError and some other object.
The WriteError
itself (from mongo-go-driver) :
// WriteError is an error that occurred during the execution of a write operation. This error type is only returned as part
// of a WriteException or BulkWriteException.
type WriteError struct {
// The index of the write-in the slice passed to an InsertMany or BulkWrite operation that caused this error.
Index int
Code int
Message string
}
During a debug session, I found out that the value of the WriteError is :
{
Index: 0
Code: 11000
Message: E11000 duplicate key error collection: auth.example index: B_1 dup key: { : "default-role-external-user" }
}
I know I always can infer the unique constraint violation via the Code
(11000), but the library didn't provide a single field to retrieve the field name causing duplication error.
I know I can always parse the Message
string as the last resort, but considering that Golang and MongoDB have been coexisting a long while and I'm sure I'm not the only one encountering this issue, I'm expecting the more robust and efficient way to retrieve the field name causing duplication error, which I'm yet to find.