Bryson Kruk Bryson Kruk - 6 months ago 26
Node.js Question

How to check if NESTED array item already exists before adding to array

I'm creating and assigning a new object id to a nested array item in Mongo, which is working great. I can't figure out how to check against that object ID to verify it doesn't already exist.

Here is the 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 it to the calback');
if(err)
res.send(err);
res.render('index', {
user: req.user,
primaryEvents: req.user.primaryEvents
});
}
);
});

Answer

You want to check that there is no value in the array with the $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 it to the calback');
                if(err)
                    res.send(err);
                res.render('index', { 
                    user: req.user,
                    primaryEvents: req.user.primaryEvents
                });
            }
        );

That will check all named properties of the sub-documents in the array and make sure that value does not exist.

So the "query" portion is where you control that. If there is already an _id with your value then there is no match and therefore no update.

Otherwise work off of something else you consider unique if you do not know the _id value, like "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 it to the calback');
                if(err)
                    res.send(err);
                res.render('index', { 
                    user: req.user,
                    primaryEvents: req.user.primaryEvents
                });
            }
        );
Comments