I have this code
var ClientSchema = new Schema({
name: {type: String, required: true, trim: true}
});
var Client = mongoose.mode(\'Client\', ClientSchema)
As of Mongoose 4.0 you can run validators on update()
and findOneAndUpdate()
using the new flag runValidators: true
.
Mongoose 4.0 introduces an option to run validators on
update()
andfindOneAndUpdate()
calls. Turning this option on will run validators for all fields that yourupdate()
call tries to$set
or$unset
.
For example, given OP's Schema:
var ClientSchema = new Schema({
name: {type: String, required: true, trim: true}
});
var Client = mongoose.model('Client', ClientSchema);
Passing the flag on each update
You can use the new flag like this:
var id = req.params.id;
var client = req.body;
Client.update({_id: id}, client, { runValidators: true }, function(err) {
....
});
Using the flag on a pre
hook
If you don't want to set the flag every time you update something, you can set a pre
hook for findOneAndUpdate()
:
// Pre hook for `findOneAndUpdate`
ClientSchema.pre('findOneAndUpdate', function(next) {
this.options.runValidators = true;
next();
});
Then you can update()
using the validators without passing the runValidators
flag every time.