Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing error in mongodb db, insert to collection with unique index

Tags:

mongodb

go

mgo

I have a collection in mongodb with documents of the form:

{
    "user": "user1",
    "email: "[email protected]",
}

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",
    "[email protected]"
}

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.

like image 730
Abimael Martinez Avatar asked Dec 26 '22 06:12

Abimael Martinez


1 Answers

http://godoc.org/labix.org/v2/mgo#IsDup

func IsDup(err error) bool

IsDup returns whether err informs of a duplicate key error because a primary key index or a secondary unique index already has an entry with the given value.

e.g.

err := users.Insert(user) // where user is type *mgo.Collection
if err != nil {
    if mgo.IsDup(err) {
        // Is a duplicate key, but we don't know which one 
    }
    // Is another error
}

Unfortunately there does not appear to be a way to discern which value is not unique in the case where you might have several unique indexes in place.

You could instead have a User struct with ID and Email instead of user and email, though. ID would be auto-generated on insert by Mongo, and Email would have a unique index. Provided you didn't need any further unique indexes you could then safely assume that an IsDup == true case means that there's a duplicate email address only.

Email addresses are good usernames as it's one less thing for users to remember ;)

like image 77
elithrar Avatar answered Apr 26 '23 02:04

elithrar