在mongodb db中解析错误,插入到具有唯一索引的集合中 [英] Parsing error in mongodb db, insert to collection with unique index
问题描述
我在mongodb中有一个集合,其文件格式为:
I have a collection in mongodb with documents of the form:
{
"user": "user1",
"email: "user1@example.com",
}
其中用户"和电子邮件"字段是唯一的.我想在集合中插入新用户,同时检查两个值的唯一性.我可以使用mgo在golang中插入以下内容:
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
如果我打印err
,它将输出insertDocument :: caused by :: 11000 E11000 duplicate key error index: kails.users.$name_1 dup key: { : "user1" }
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.
如果无法使用该错误查找是否不是唯一的,那么"$ or"查询(检查唯一性)+插入是否有其他选择?
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?
我已经阅读了 mgo文档,希望我不要错过任何重要的内容
I've read the mgo documentation, hope I didn't miss anything important.
推荐答案
http://godoc.org/labix .org/v2/mgo#IsDup
func IsDup(err error) bool
IsDup返回err是否通知重复的键错误,因为主键索引或辅助唯一索引已经具有具有给定值的条目.
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.
例如
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.
尽管如此,您可以改为使用ID
和Email
而不是user
和email
的User结构. ID将在Mongo插入时自动生成,而Email将具有唯一索引.如果您不需要其他唯一索引,则可以放心地假设IsDup == true
情况意味着只有重复的电子邮件地址.
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 ;)
这篇关于在mongodb db中解析错误,插入到具有唯一索引的集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!