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

自古美人都是妖i 提交于 2019-12-05 14:51:58

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 ;)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!