2
votes

I have a MongoDB collections with various documents. Now I have the input document Ids in an array of cars which I want to update. Something like this.

req.body = 
{ cars: [ '584cf6c126df866138a29408', '5852819e9693c27c136104bd' ],
    name: 'Home' },
{ cars: [ '584d638242795854a091cbbf', '5842e09e372b786355ba50e7' ],
    name: 'Office' } ]

Expected Operation

db.cars.update({_id : req.body[i].cars}, {name : req.body[i].name}, {new : true});

Expected Result
All four documents with ids are updated with their name field in the document.

Now one way to update cars is to have an async.each applied on the array and an aysnc.each on these two documents. That's the longer way of doing it. I was hoping if I have one async.each for these two arrays and somehow could cramp both the documents in a single query it would make the code look more elegant. I have already gone through several pages and still haven't found anything wanted to know if this is possible in mongo or not?

2
can you provide the expected output? I'm not sure to understand what you want to achievefelix
did you try $eachYogesh
@Yogesh $each is an array update operation. I wanted to update each and every document represted by the array in the req.body field.Saras Arya

2 Answers

2
votes

At first you may need to convert your car ids String type to mongodb ObjectId that means like:

cars: [ ObjectId'584cf6c126df866138a29408'), ObjectId'5852819e9693c27c136104bd') ]

then use $in operator to match with documents.

can try this.

var ObjectId = require('mongodb').ObjectID;
var cars = req.body[i].cars.map(function (id) {
  return new ObjectId(id);
})

db.cars.update({_id : {$in: cars}}, 
  {$set : {name : req.body[i].name}},
  {multi : true},
  function(err, docs) {
    console.log(docs);
});
1
votes

Try using $in of mongodb in find query while doing update. See query below:

Model.update({_id : {$in: req.body[i].cars}}, 
 {$set : {name : req.body[i].name}},
 {multi : true});

So this way you have to run 2 queries to update the names.

See $in-doc to know more about the uses.

Hope this will help you.