Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 992
Aryan Avatar asked Jan 14 '16 01:01

Aryan


People also ask

How do you update an array of objects in MongoDB using node JS?

To perform an update on all embedded array elements of each document that matches your query, use the filtered positional operator $[<identifier>] . The filtered positional operator $[<identifier>] specifies the matching array elements in the update document.

Can we update _ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.


1 Answers

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}}, ...);
like image 59
JohnnyHK Avatar answered Sep 22 '22 07:09

JohnnyHK