如何检查Mongo的$ addToSet是否重复

dga*_*ant 5 mongodb node.js mongoskin

我使用Mongoskin + NodeJS向MongoDB添加新关键字.我想通知用户该条目是重复的,但不知道如何执行此操作.

/*
* POST to addkeyword.
*/
router.post('/addkeyword', function(req, res) {
var db = req.db;
db.collection('users').update({email:"useremail@gmail.com"}, {'$addToSet': req.body }, function(err, result) {
    if (err) throw err;
    if (!err) console.log('addToSet Keyword.' );
}); 
});
Run Code Online (Sandbox Code Playgroud)

结果似乎没有任何用处,因为它没有告诉我是否添加了关键字.

Seb*_*ian 4

至少在 shell 中您可以区分文档是否被修改(请参阅 参考资料nModified)。

> db.test4.update({_id:2}, {$addToSet: {tags: "xyz" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.test4.update({_id:2}, {$addToSet: {tags: "xyz" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
Run Code Online (Sandbox Code Playgroud)

节点更新

使用时,collection.update(criteria, update[[, options], callback]);您可以检索已修改的记录数。

来自节点文档

回调是更新记录后要运行的回调。有两个参数,第一个是错误对象(如果发生错误),第二个是被修改的记录数

另一个更新

看来至少在 1.4.3 版本中,本机 Mongo Node 驱动程序的行为并不像文档中描述的那样。可以使用批量 API(在 Mongo 2.6 中引入)来解决:

var col = db.collection('test');
// Initialize the Ordered Batch
var batch = col.initializeOrderedBulkOp();
batch.find({a: 2}).upsert().updateOne({"$addToSet": {"tags": "newTag"}});
// Execute the operations
batch.execute(function(err, result) {
  if (err) throw err;
  console.log("nUpserted: ", result.nUpserted); 
  console.log("nInserted: ", result.nInserted); 
  console.log("nModified: ", result.nModified); // <- will tell if a value was added or not
  db.close();
});
Run Code Online (Sandbox Code Playgroud)