Siddhartha Chowdhury Siddhartha Chowdhury - 1 month ago 6
Node.js Question

Mongoose, Add/Update data to a set of documents of a collection

Hello guys here's the situation of my problem:

My

Categories
model looks like this:

schema: {
_id: String,
name: String,
overview: String,
courses: [
{
_id: String,
name: String
}
]
}


I have multiple categories recorded, in the above collection
Categories


WHAT I NEED

I have an [ array ] of
Categories._id
like this:

[
'5812f3cb04700f2563c0e56a',
'5812f3ff04700f2563c0e56b',
...
]


All I want is to
PUSH
this object
{_id:5812f3ff04700f2563c0e56b, name:'SOMETHING' }
to all the documents listed in the array of
_id


WHAT I TRIED

Categories.update({
'_id': {
$in : array_of_IDs
}
},
{
$push :{
'courses':{ _id: ret._id , name: ret.title }
}
}, function(err, respp){
if(err) return res.negotiate(err);
else{
req.addFlash('success', 'Categories updated successfully.');
return res.redirect('/new-course');
}
}
);


This above code is updating only one collection (the collection with 1st ID in the array of IDs)

Please help!

Thanks

Answer

can try using multi: true as option

Categories.update({
        '_id': {
            $in : array_of_IDs
        } 
    },
    {
        $push :{
            'courses':{ _id: ret._id , name: ret.title }
        }
    },{ multi: true }, function(err, respp){
        //....
    }
);
Comments