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.
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.
You cannot update it but you can save a new id and remove the old id.
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}}, ...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With