【问题标题】:Parsing error in mongodb db, insert to collection with unique indexmongodb db中的解析错误,插入到具有唯一索引的集合中
【发布时间】:2014-09-06 12:31:58
【问题描述】:

我在 mongodb 中有一个包含以下形式的文档的集合:

{
    "user": "user1",
    "email: "user1@example.com",
}

“用户”和“电子邮件”字段是唯一的。我想在集合中插入一个新用户,同时检查两个值的唯一性。我可以像这样使用 mgo 在 golang 中插入:

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

如果我打印err,它会输出insertDocument :: caused by :: 11000 E11000 duplicate key error index: kails.users.$name_1 dup key: { : "user1" }

是否有一种惯用的方法可以使用此错误来查找哪些值不是唯一的?如果不是两者都存在? (或者是否需要其他步骤?)。使用正则表达式解析字符串感觉...错误。

如果无法使用错误来查找是否不唯一,是否有任何替代“$or”查询(检查唯一)+插入的方法?

我已经阅读了mgo documentation,希望我没有错过任何重要的内容。

【问题讨论】:

  • 您是如何使这些字段独一无二的?
  • 你在哪里提到你的独特字段Email id

标签: mongodb go mgo


【解决方案1】:

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

func IsDup(err error) bool

IsDup 返回 err 是否通知重复键错误,因为主键索引或辅助唯一索引已经具有具有给定值的条目。

例如

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
}

不幸的是,在您可能有多个唯一索引的情况下,似乎没有办法辨别哪个值不是唯一的。

不过,您可以使用带有 IDEmail 的 User 结构,而不是 useremail。 ID 将在 Mongo 插入时自动生成,并且电子邮件将具有唯一索引。如果您不需要任何其他唯一索引,那么您可以安全地假设 IsDup == true 案例意味着只有一个重复的电子邮件地址。

电子邮件地址是很好的用户名,因为它是用户记住的少一件事;)

【讨论】:

  • 其实“user”变量存储的是网名,所以我确实需要检查一下。但这会做,我想我会先检查一下,然后再插入。
  • Unfortunately there does not appear to be a way to discern which value is not uniquemgo 库是否有针对此问题的更新?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
相关资源
最近更新 更多