vignesh vignesh - 29 days ago 14
Node.js Question

Selecting only modified subdocument from Mongo

I have a mongoose query like this:

var query = Events.findOneAndUpdate({ '_id': event._id,'participants._id':participant._id},{'$set': {'participants.$': participant}}, {upsert:false,new: true},function(err,result){
if(err){
return res.status(500).jsonp({
error: 'Unable to update participant'
});
}
console.log(result.participants[0]);
res.jsonp(result.participants[0]);
});


and the query works properly modifying the participants subdocument inside Events collection.

The problem:

I need only the modified participant to be returned as JSON and I am not in need of the entire participants array but I am not able to achieve this since I get all the participants when I do
console.log(result.participants);


How do I get only the modified subdocument after the query?

Answer

You may have to use the native JS filter() method as in the following:

Events.findOneAndUpdate(
    { '_id': event._id, 'participants._id': participant._id },
    { '$set': { 'participants.$': participant } }, 
    { upsert: false, new: true },
    function(err, result){
        if(err){
            return res.status(500).jsonp({
                error: 'Unable to update participant'
            });
        }
        var modified = result.participants.filter(function(p){
            return p._id === participant._id
        })[0];
        console.log(modified);
        res.jsonp(modified);
    }
);