Aryan
Aryan

Reputation: 75

Updating multiple MongoDB objects by their unique _id using Node.js

Basically I'm trying to update multiple objects on my Mongo database based on their unique objectID (_id). I tried the followings but they did not work:

  var new_arr = [];
  for (var i = 0; i < req.body.length; i++) {
    // req.body is an array received from the POST request.
    new_arr.push({"_id": new mongodb.ObjectID(req.body[i])})
  }
  console.log(new_arr);

  // new_arr is not accepted since an object is expected.
  job_applications.updateMany(
      new_arr
      ,
      {
        $set: {"application_status": "rejected"}
      }, function (err, results) {
        console.log(results);
        console.log(err);
        if (!err) {
          console.log('success with reject');
          res.sendStatus(200);
        }
      }
  );

I also tried the following with no luck.

var job_applications = req.app.locals.job_applications;
  var new_arr = [];
  for (var i = 0; i < req.body.length; i++) {
    // req.body is an array of unique IDs (_id)
    new_arr.push(new mongodb.ObjectID(req.body[i]))
  }
  var send_obj = {
    "_id": new_arr
  };
  job_applications.updateMany(
      send_obj
      ,
      {
        $set: {"application_status": "rejected"}
      }, function (err, results) {
        console.log(results);
        console.log(err);
        if (!err) {
          console.log('success with reject');
          res.sendStatus(200);
        }
      }
  );

The only solution I found to this problem was to send multiple updateOne() requests for each object to MongoDB but that is very inefficient. I believe there must be a more efficient solution to this problem. Any help/guidance is much appreciated.

Upvotes: 6

Views: 2968

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312055

You're close with the second one, but you need to use the $in query operator to match _id against an array of possible values:

var new_arr = [];
for (var i = 0; i < req.body.length; i++) {
    new_arr.push(new mongodb.ObjectID(req.body[i]))
}
job_applications.updateMany({_id: {$in: new_arr}}, ...);

Upvotes: 7

Related Questions