Saloni Malhotra
2 min readAug 7, 2017

Update Multiple documents in Mongoose

I was working on office Project & i have to update Multiple Documents functionality in mongoose.

So the Following Approach i was follow to update Multiple documents ….here below my User Schema

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) i.e 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.

Hi, My name is Saloni Malhotra. I am a Javascript Developer and writer. I am here to talk so Don’t hesitate to Drop me a message.if you like my story Please Click ❤ and share with everyone.

Thanks !!
Happy coding

Saloni Malhotra

I write about web development, Answers questions on Quora. Solving people problems using code spells. Web developer, Writer, Thinker.