I have a collection in mongodb with documents of the form:
{
"user": "user1",
"email: "user1@example.com",
}
Where the fields "user" and "email" are unique. I want to insert a new user to the collection, while checking for uniqueness of both values. I can do an insert in golang with mgo like this:
session.SetSafe(&mgo.Safe{}) // ensure mgo waits for errors
user := struct{
string `bson:"user"`
string `bson:"email"`
}{
"user1",
"user1@different.com"
}
err := users.Insert(user) // where user is type *mgo.Collection
If I print err
it outputs insertDocument :: caused by :: 11000 E11000 duplicate key error index: kails.users.$name_1 dup key: { : "user1" }
Is there an idiomatic way to use this error to find which of the values wasn't unique?, if not both? (or are there other steps needed?). Parsing the string using a regexp feels... wrong.
If it's not possible to use the error to find if not unique, are there any alternatives to an "$or" query (check for unique) + insert?
I've read the mgo documentation, hope I didn't miss anything important.