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.
$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.
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.
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 ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With