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

我正在使用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.' ); }); }); 

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

至less在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 }) 

更新节点

当你使用collection.update(criteria, update[[, options], callback]); 您可以检索修改logging的数量。

从节点文档

callback是logging更新后要运行的callback。 有两个参数,第一个是错误对象(如果发生错误),第二个是已修改logging计数

另一个更新

至less在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(); }); 

您可以使用db.users.findAndModify({email:"useremail@gmail.com"},[],{'$addToSet': { bodies: req.body }},{'new':false}) 。 注意new:false switcher,它允许你在更新之前获取文档,并且可以在更新之前检查数组是否包含项目。 但是,如果您的文档很大,可能会出现问题,因为您在客户端进行分析。

PS你原来的查询与$ addToSet是错误的:字段名称丢失。

编辑:我试图使用update返回计数,但它在所有情况下返回1。 这里是我用于testingMongoDB 2.6的代码:

 var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/mtest', function(err, db) { if(err) throw err; db.collection('test').insert({_id:1,bodies:["test"]},function(err,item){ db.collection('test').update({_id:1},{$addToSet:{bodies:"test"}}, function(err,affected){ if(err) throw err; console.log(affected); //1 in console }); }); });