mgo/txn 声明集合中的唯一性
mgo/txn assert uniqueness in collection
我一直在尝试将用户信息插入我的 mongodb。因为我希望用户名和电子邮件都是唯一的,所以我为它创建了一个电子邮件代理集合。
userID := bson.NewObjectId()
emailID := bson.NewObjectId()
tc := mgoSession.DB(DBName).C("transaction")
runner := txn.NewRunner(tc)
ops := []txn.Op{{
C: "email",
Id: emailID,
Assert: txn.DocMissing,
Insert: Email{ParentID: userID, Email: email},
}, {
C: "user",
Id: userID,
Assert: txn.DocMissing,
Insert: User{ID: userID, Username: username, Email: email, RegDate: time.Now(), HashedPw: hashedpw},
}}
err = runner.Run(ops, "", nil)
if err != nil {
panic(err)
}
我想在插入之前声明操作 1 的电子邮件的唯一性和操作 2 的用户名的唯一性。我想我没有使用 txn.DocMissing 权利,但我在互联网上找不到太多关于它的信息。
来自文档
// DocExists and DocMissing may be used on an operation's
// Assert value to assert that the document with the given
// Id exists or does not exist, respectively.
...
// Insert holds the document to be inserted at the time the
// transaction is applied. The Id field will be inserted
// into the document automatically as its _id field. The
// transaction will continue even if the document already
// exists. Use Assert with txn.DocMissing if the insertion is
// required.
所以我觉得如果使用 txn.DocMissing 则必须插入该项目才能完成交易。如果插入失败,则事务将回滚。我认为这与独特性无关。为此,您可能需要使用唯一索引
https://docs.mongodb.com/manual/core/index-unique/
还有关于断言如何工作的更多信息
https://blog.labix.org/2012/08/22/multi-doc-transactions-for-mongodb
我一直在尝试将用户信息插入我的 mongodb。因为我希望用户名和电子邮件都是唯一的,所以我为它创建了一个电子邮件代理集合。
userID := bson.NewObjectId()
emailID := bson.NewObjectId()
tc := mgoSession.DB(DBName).C("transaction")
runner := txn.NewRunner(tc)
ops := []txn.Op{{
C: "email",
Id: emailID,
Assert: txn.DocMissing,
Insert: Email{ParentID: userID, Email: email},
}, {
C: "user",
Id: userID,
Assert: txn.DocMissing,
Insert: User{ID: userID, Username: username, Email: email, RegDate: time.Now(), HashedPw: hashedpw},
}}
err = runner.Run(ops, "", nil)
if err != nil {
panic(err)
}
我想在插入之前声明操作 1 的电子邮件的唯一性和操作 2 的用户名的唯一性。我想我没有使用 txn.DocMissing 权利,但我在互联网上找不到太多关于它的信息。
来自文档
// DocExists and DocMissing may be used on an operation's
// Assert value to assert that the document with the given
// Id exists or does not exist, respectively.
...
// Insert holds the document to be inserted at the time the
// transaction is applied. The Id field will be inserted
// into the document automatically as its _id field. The
// transaction will continue even if the document already
// exists. Use Assert with txn.DocMissing if the insertion is
// required.
所以我觉得如果使用 txn.DocMissing 则必须插入该项目才能完成交易。如果插入失败,则事务将回滚。我认为这与独特性无关。为此,您可能需要使用唯一索引
https://docs.mongodb.com/manual/core/index-unique/
还有关于断言如何工作的更多信息 https://blog.labix.org/2012/08/22/multi-doc-transactions-for-mongodb