How to check if Mongo's $addToSet was a duplicate or not

前端 未结 3 2095
南方客
南方客 2021-01-13 04:15

I am using Mongoskin + NodeJS to add new keywords to MongoDB. I want to notify the user that the entry was a duplicate but not sure how to do this.

/*
* POST          


        
3条回答
  •  遥遥无期
    2021-01-13 04:28

    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:

    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
    
        });
     });
    
    });
    

提交回复
热议问题