5

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.

Hamada
  • 1,836
  • 3
  • 13
  • 27
imeluntuk
  • 385
  • 1
  • 5
  • 15

2 Answers2

1

The short and saddening answer is that currently there isn't a better way with the official mongo-go driver.

icza
  • 389,944
  • 63
  • 907
  • 827
  • Wait so devs actually use hackish way like parse the err message string to overcome this issue? – imeluntuk Jul 03 '20 at 11:44
  • @icza This is the shortest answer I see from you ! – Eklavya Jul 03 '20 at 12:05
  • @imeluntuk I don't know if they use this or not. It's rarely needed. – icza Jul 03 '20 at 12:23
  • 2
    @Eklavya The asker posted a well-researched question and pretty much listed his / her viable options, and was asking if there is an easier way. And there is not. So I think currently this answer is what "there is to it". – icza Jul 03 '20 at 12:39
0

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.

D. SM
  • 13,584
  • 3
  • 12
  • 21