[Mongoose] Setting validation runValidators: true in update() and findOneAndUpdate()
Mongoose’s update() and findOneAndUpdate() don’t run validators by default, but you can run validators by specifying the runValidators: true option.
Update ValidatorsIn the above examples, you learned about document validation. Mongoose also supports validation for update() and findOneAndUpdate() operations. Update validators are off by default - you need to specify the runValidators option.
To turn on update validators, set the runValidators option for update() or findOneAndUpdate(). Be careful: update validators are off by default because they have several caveats.
var toySchema = new Schema({ color: String, name: String }); var Toy = db.model('Toys', toySchema); Toy.schema.path('color').validate(function (value) { return /blue|green|white|red|orange|periwinkle/i.test(value); }, 'Invalid color'); var opts = { runValidators: true }; Toy.updateOne({}, { color: 'bacon' }, opts, function (err) { assert.equal(err.errors.color.message, 'Invalid color'); });
Here’s the Japanese translation of the above:
Mongoose では update() および findOneAndUpdate() でも validation をサポートしています。Update validator はデフォルトではオフです。Update validator を実行するには runValidators オプションを指定する必要があります。
Update validator を有効にするには、update() または findOneAndUpdate() に対して runValidators オプションを設定します。
[注意]:いくつかの警告があるので、Update validator はデフォルトでオフです。
Mongoose supports validation for update() and findOneAndUpdate() operations. Update validators are off by default. To run update validators, you need to specify the runValidators option.
To enable update validators, set the runValidators option for update() or findOneAndUpdate().
[Note]: Update validators are off by default because they have several caveats.
That’s all from the Gemba.