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

时间:2017-12-30 04:20:25

标签: mongodb go mgo

我一直在尝试将用户信息插入我的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,但我在互联网上找不到太多关于它的信息。

1 个答案:

答案 0 :(得分:1)

来自文档

// 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