问题
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.
回答1:
The short and saddening answer is that currently there isn't a better way with the official mongo-go driver.
回答2:
Applications that need to know whether a value in a unique field is already taken usually query the database for that value, rather than parsing the message returned by the server as you are asking.
This situation is not specific to MongoDB or Go - I am not aware of any MongoDB driver that parses unique index violations out of error messages, and I haven't heard of this being done for relational databases either.
来源:https://stackoverflow.com/questions/62711694/with-mongo-go-driver-how-do-i-efficiently-retrieve-duplicated-field-name-from-w