gpt4 book ai didi

mongodb - mgo/txn 断言集合中的唯一性

转载 作者:数据小太阳 更新时间:2023-10-29 03:12:21 25 4
gpt4 key购买 nike

我一直在尝试将用户信息插入到我的 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/

还有关于 Assert 工作原理的更多信息 https://blog.labix.org/2012/08/22/multi-doc-transactions-for-mongodb

关于mongodb - mgo/txn 断言集合中的唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com