Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple documents by id set. Mongoose

I wonder if mongoose has some method to update multiple documents by id set. For example:

for (var i = 0, l = ids.length; i < l; i++) {     Element.update({'_id': ids[i]}, {'visibility': visibility} ,function(err, records){         if (err) {             return false;         } else {             return true;         };     }); }; 

What i want to know, that if mongoose can do something like this:

Element.update({'_id': ids}, {'visibility': visibility}, {multi: true} ,function(err, records){     if (err) {         return false;     } }); 

where ids is an array of ids, like ['id1', 'id2', 'id3'] - sample array. Same question for find.

like image 221
user2960708 Avatar asked Nov 20 '13 13:11

user2960708


People also ask

How can I update multiple documents in Mongoose?

$in -The $in operator selects the documents where the value of a field equals any value in the specified array. 1) {multi:true} to update Multiple documents in mongoose . 2)use update query to update Multiple documents ,If you are using findOneAndUpdate query only one record will be updated.

How do I update multiple files in MongoDB?

You can update multiple documents using the collection. updateMany() method. The updateMany() method accepts a filter document and an update document. If the query matches documents in the collection, the method applies the updates from the update document to fields and values of the matching documents.

What is the difference between id and _ID in Mongoose?

So, basically, the id getter returns a string representation of the document's _id (which is added to all MongoDB documents by default and have a default type of ObjectId ). Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an ObjectId or a string ).


1 Answers

Most probably yes. And it is called using $in operator in mongodb query for update.

db.Element.update(    { _id: { $in: ['id1', 'id2', 'id3'] } },    { $set: { visibility : yourvisibility } },    {multi: true} ) 

All you need is to find how to implement $in in mongoose.

like image 144
Salvador Dali Avatar answered Sep 17 '22 11:09

Salvador Dali