gpt4 book ai didi

node.js - 如何检查 Mongo 的 $addToSet 是否重复

转载 作者:IT老高 更新时间:2023-10-28 12:29:02 24 4
gpt4 key购买 nike

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

结果似乎没有任何用处,因为它没有说明是否添加了关键字。

最佳答案

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

Node 更新

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

从 Node docs

callback is the callback to be run after the records are updated. Has two parameters, the first is an error object (if error occured), the second is the count of records that were modified.

另一个更新

似乎至少在 1.4.3 版本中, native 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();
});

关于node.js - 如何检查 Mongo 的 $addToSet 是否重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23544366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com