Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to push a new document in mongodb but only if it does not exist?

How to push a new document in mongodb but only if it does not exist?

Problem

I have a POST being done that uses this code:

exports.addContactPost = function(req, res, err) {
    User.findByIdAndUpdate(req.signedCookies.userid, {
                $push: {friendRequest: req.body.friendRequest}
            }, function(err) {
                if(err) {
                    console.log(err);
                    return console.log('error'); 
                } else {            
                    console.log('postsuccess');
                    res.json({response: true});
                    }
            });
};

How can I take the $push: line of code and state that if the id already exists in the array of friendRequest that do not Push. I was trying to use $exist: but I could not get it to work.

Problem courtesy of: Lion789

Solution

Use the $addToSet operator. It ensures that the value will be added if is not in the array already.

Basically:

exports.addContactPost = function(req, res, err) {
    User.findByIdAndUpdate(req.signedCookies.userid, {
                $addToSet: {friendRequest: req.body.friendRequest}
            }, function(err) {
                if(err) {
                    console.log(err);
                    return console.log('error'); 
                } else {            
                    console.log('postsuccess');
                    res.json({response: true});
                    }
            });
};
Solution courtesy of: Miguel Cartagena

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to push a new document in mongodb but only if it does not exist?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×