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

I am basically trying to update multiple objects in my Mongo database based on their unique objectID (_id). I tried the following steps, 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 for this problem is to send multiple updateOne () requests for each object in MongoDB, but this is very inefficient. I believe that there should be a more effective solution to this problem. Any help / guidance is greatly appreciated.

+5
source share
1 answer

You are close to the second, but you need to use the $in query operator to match _id for 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}}, ...); 
+5
source

Source: https://habr.com/ru/post/1240584/


All Articles