drdawt9210 2014-07-16 05:42
浏览 104
已采纳

在mongodb db中解析错误,插入到具有唯一索引的集合中

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.

  • 写回答

1条回答 默认 最新

  • douyue6520 2014-07-16 08:07
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题