node.js - How to check if NESTED array item already exists before adding to array -
i'm creating , assigning new object id nested array item in mongo, working great. can't figure out how check against object id verify doesn't exist.
here route:
router.post('/events', function(req,res){ var loggedinuser = req.user.username; var objectid = new objectid(); user.update( {"username" : loggedinuser}, { $push:{ primaryevents:{ _id: objectid, name: req.body.name, date: req.body.date, description: req.body.description } } }, {upsert:true}, function(err){ console.log('made calback'); if(err) res.send(err); res.render('index', { user: req.user, primaryevents: req.user.primaryevents }); } ); });
you want check there no value in array $ne
inequality operator:
user.update( { "username" : loggedinuser, "primaryevents._id": { "$ne": objectid } }, { $push:{ primaryevents:{ _id: objectid, name: req.body.name, date: req.body.date, description: req.body.description } } }, {upsert:true}, function(err){ console.log('made calback'); if(err) res.send(err); res.render('index', { user: req.user, primaryevents: req.user.primaryevents }); } );
that check named properties of sub-documents in array , make sure value not exist.
so "query" portion control that. if there _id
value there no match , therefore no update.
otherwise work off of else consider unique if not know _id
value, "name":
user.update( { "username" : loggedinuser, "primaryevents.name": { "$ne": req.body.name } }, { $push:{ primaryevents:{ _id: objectid, name: req.body.name, date: req.body.date, description: req.body.description } } }, {upsert:true}, function(err){ console.log('made calback'); if(err) res.send(err); res.render('index', { user: req.user, primaryevents: req.user.primaryevents }); } );
Comments
Post a Comment