I am using Mongoskin + NodeJS to add new keywords to my MongoDB. I want to notify the user that the entry was a duplicate but not sure how to do this.
/*
* 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.' );
});
});
The result does not seem to be of any use to me since it doesn't tell me if the keyword was added or not.
At least in the shell you can differentiate if the document was modified or not (see
nModified
).Update for Node
When you use
collection.update(criteria, update[[, options], callback]);
you can retrieve the count of records that were modified.From the node docs
Another Update
It seems at least in version 1.4.3 the native Mongo Node driver is not behaving as documented. It is possible to work around using the bulk API (introduced in Mongo 2.6):
You could use
db.users.findAndModify({email:"useremail@gmail.com"},[],{'$addToSet': { bodies: req.body }},{'new':false})
. Pay attention to new:false switcher, it allows you to get document before update and you could check whether array contained item before update. However, it could be problematic approach if your documents are big, because you analyze it on client side.P.S. Your original query with $addToSet is wrong: field name is missing.
Edit: I tried to use count returned by
update
, but it returns 1 for me in all cases. Here is the code I used for test with MongoDB 2.6: