Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple documents by providing documents in body, mongoose/mongodb

I need to update several documents by providing them in the body. I can't query them, they must be provided.

Example:

 var persons = [
    {id: 1, name'Joe', active: false}, 
    {id:2, name:'Jane', active: false})
];

This data is provided in the body and I want to set the active property to false.

exports.setActivePropertyOnPersons = function(input,callback){
  for(var i = 0;i<input.body.length;i++){
    mongoose.model('person').findOne({id:input.body[i].id}, function(err, person){
      person.active = false;
      person.save();
    })
  }
  callback.send(200)
};

This code feels no good. Is there any better query to do this? I don't find any in the docs.

like image 786
Joe Avatar asked Nov 01 '14 12:11

Joe


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 Upsert in Mongoose?

Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.


1 Answers

Try using the update command along with the "$in" operator:

var ids= [];
for (var i=0 i<input.body.length; ++i) {
    ids.push(input.body[i].id);
}

mongoose.model('person').update( {id : {"$in":ids}}, {active:false} , {multi: true} , function(err,docs) { ... });

Hope this helps

like image 121
Protostome Avatar answered Sep 29 '22 13:09

Protostome