Why Mongoose doesn't validate on update?

后端 未结 6 2513
故里飘歌
故里飘歌 2020-11-30 00:07

I have this code

var ClientSchema = new Schema({
  name: {type: String, required: true, trim: true}
});

var Client = mongoose.mode(\'Client\', ClientSchema)         


        
6条回答
  •  既然无缘
    2020-11-30 01:06

    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() and findOneAndUpdate() calls. Turning this option on will run validators for all fields that your update() 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.

提交回复
热议问题