Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb mgo/txn在集合中断言唯一性_Mongodb_Go_Mgo - Fatal编程技术网

Mongodb mgo/txn在集合中断言唯一性

Mongodb mgo/txn在集合中断言唯一性,mongodb,go,mgo,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",

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

来自文档

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

因此,在我看来,如果使用txn.DocMissing,则必须插入该项才能完成事务。如果插入失败,则事务将回滚。我认为这与独特性无关。为此,您可能需要使用唯一索引

还提供了有关Assert如何工作的更多信息

我已经为这些字段创建了唯一索引。但是,如果插入失败,事务不会返回err。它只会将事务插入到事务集合中。插入到用户和电子邮件中的记录也会有txn队列和txn revno。我不太熟悉mongo和事务。你可能把它复杂化了。如果你有唯一的ID,那么做一个简单的插入就可以了。如果您需要同时进行两次插入。。只需使用方法包装两个插入。->类似->func(ids…)insert()errorMongo的东西也不是sql。您可以重新设计文档以包含所有必要的信息。以后进行两次单独的查找没有意义。从上面可以看到,我没有规范化我的mongodb表。我只是按照创建多个唯一字段,所以我必须创建一个额外的表,以实现电子邮件的唯一性。由于这两个插入是密切相关的,我必须使用事务来确保它们的完成。@MarkusWMahlberg我明白你的观点,我们应该避免mgo/txn。我刚刚发现我误解了docs.mongodb.com/manual/tutorial/unique-constraints-on-arbitral-fields/。实际上,我可以为一个集合创建两个唯一的索引。谢谢你花这么多时间。我会将此标记为答案。请向您展示实际的数据模型并描述您的用例。
// 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.