简体   繁体   中英

how to update multiple documents in mongodb using node Based on unique id

How can update multiple docs in mongoose, I aware of how to update multiple docs which matches with other docs, but I want update multiple docs to be updated using the id.

I tried many ways, Here is one of it.

Updated

var myid = req.params.noteId

   Note.updateMany({ _id:{ $in:ObjectID(myid) } }, {

       lname: req.body.lname || "Untitled Note",
       age: req.body.age
   }, { new: true })
       .then(note => {
           if (!note) {
               return res.status(404).send({
                   message: "Note not found with id " + req.params.noteId
               });
           }
           res.send(note);
       })

And One more thing How can I pass multiple Ids as parameters to update multiple docs in a postman tester.

mongoose.Types.ObjectId.isValid will return boolean value. check this https://github.com/mongodb/js-bson/blob/f7efecc04240525931402116f881b5984af800c4/lib/bson/objectid.js#L247

If you want update for multiple ids to pass those ids inside req.body

for multiple use $in else pass directly.

var myid = req.params.noteId;

if (mongoose.Types.ObjectId.isValid(myid)) {
    Note.update({
            _id: mongoose.Types.ObjectId(myid)
           // _id: {$in: req.body.somekey_array.map(id => mongoose.Types.ObjectId(id ))} //multiple
        }, {

            lname: req.body.lname || "Untitled Note",
            age: req.body.age
        }, {
            multi: true //multiple
        })
        .then(note => {
            console.log('----qqqqq--', note)
            if (!note) {
                return res.status(404).send({
                    message: "Note not found with id " + req.params.noteId
                });
            }
            res.json(note);
        });
} else {
    res.status(400).json({
        msg: 'id not correct'
    });
}

First Step:-

var Mongoose = require(‘mongoose’),
 Schema = Mongoose.Schema;
var UserSchema = new Schema({
 firstName: { type: String, required: true },
 profile_pic: { type: String, default: null},
 city:{type:String},
 country:{type:String},
 occupation:{type:String},
 address:{type: String },
 email: { type: String, unique: true, required: true },
 password: { type: String, required: true },
 mobile_number: { type: String, required: true },
created_at: { type: Date, default: Date.now },
status:{type: Number, default: 0} // status: 0 — Active ,1 -Deactive
});
var user = Mongoose.model(‘user’, UserSchema, ‘users’);
module.exports = {
 User: user
};

Activate or Deactivate user according to their status.In User Schema, i was already set status to 0(zero) ie currently all the users was activate.

Second Step:- In routes i was taken values on the basis of these two & updating my User Schema.You can take two or more values in your routes according to your requirements.

_id: Joi.string().required(),
status: Joi.number().required(),

Third Step:-

var criteria = {
 _id:{ $in: request.payload.split(‘,’)}
};
Models.users.User.update(criteria, { status: true }, { multi: true }, function(err, res) {
 if (err) { callback(err, null);
 } else { callback(null, res);
 });

$in -The $in operator selects the documents where the value of a field equals any value in the specified array. split -Split a string into an array of substrings Note-Please use

1) {multi:true} to update Multiple documents in mongoose .

2) use update query to update Multiple documents, If you are using findOneAndUpdate query only one record will be updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM