确认$ addToSet添加一个元素

时间:2014-06-10 22:31:31

标签: node.js mongodb

我有一个函数通过$ addToSet将一堆数据添加到db中,如果数据已添加,我需要确认。由于$ addToSet不添加重复项,我想知道是否没有添加重复项(向用户显示错误)或者是否添加了数据库条目(向用户显示确认)。

我基本上需要回调$ addToSet操作。无法在文档中找到它。 mongodb新手。非常感谢帮助。

_notifications.update(
        {'username': data.username}, 
        { $addToSet: pushNotification }, function(err, docs){
            console.log(docs);
            if (docs == 0){
                co_notifications.insert(
                    {'username': data.username, 'notifications': insertNotification}, function(er, doc){
                });
            }
        },
        { upsert: true }
    );

1 个答案:

答案 0 :(得分:1)

我可能会遗漏一些东西,但我唯一能看到的是新批处理操作API的结果。

var mongodb = require('mongodb'),
    MongoClient = mongodb.MongoClient;


MongoClient.connect("mongodb://localhost/test",function(err,db) {

  var col = db.collection("mytest");
  var batch = col.initializeOrderedBulkOp();


  batch.find({ "user": "me" }).upsert().updateOne({ "$addToSet": { "list": 5 } });
  batch.execute(function(err,result) {
    console.log( JSON.stringify( result, undefined, 4 ) );
  });

});

在该样本列表中,您第一次执行"结果"的内容会像这样转储:

{
    "ok": 1,
    "writeErrors": [],
    "writeConcernErrors": [],
    "nInserted": 0,
    "nUpserted": 1,
    "nMatched": 0,
    "nModified": 0,
    "nRemoved": 0,
    "upserted": [
        {
            "index": 0,
            "_id": "5397ae995f04804cbeb7c663"
        }
    ]
}

值得注意的关键是" nUpserted"并且" upserted"每个创建的文档的数组。尽管我们这样做了,但它仍然是一个批处理操作。

在第二次执行时,它应该找到现有文档并且还匹配set成员,你会得到这个:

{
    "ok": 1,
    "writeErrors": [],
    "writeConcernErrors": [],
    "nInserted": 0,
    "nUpserted": 0,
    "nMatched": 1,
    "nModified": 0,
    "nRemoved": 0,
    "upserted": []
}

这表明虽然文档是匹配的,但实际上并没有修改任何内容,因为set成员是相同的。但是,如果您将 $addToSet 操作中应用的值更改为不存在的内容,则响应将为:

{
    "ok": 1,
    "writeErrors": [],
    "writeConcernErrors": [],
    "nInserted": 0,
    "nUpserted": 0,
    "nMatched": 1,
    "nModified": 1,
    "nRemoved": 0,
    "upserted": []
}

这显示了" nMatched"和" nModified"表示文档的值实际上是由 $addToSet 操作更新的。

所以这可能是一种可能的方法

相关问题