简体   繁体   中英

Mongoose conditional required field

The schema should be defined, so that an attribute b is required iff the attribute a is set to false.

const { Schema, model } = require("mongoose");

const schema = new Schema({
  a: { type: Boolean, default: false },
  b: {
    type: Number,
    required: function () {
      return !this.a;
    }
  }
});

const Model = model("bla", schema);

Model.validate({a: true});

But if I define the schema as above, the validate call in the last line will throw an error that b is required, even if a is set to false :

ValidationError: Validation failed: b: Path `b` is required.

The problem thems to be, that this is not referring to the schema, but to the function and there is no value a defined, so the function will only evaluate to true and b is always required.

With Model.validate() , you need to pass the context as the third parameters to make it work correctly. Something like Model.validate({a: true}, ['b'], {a: true}) as mentioned in this issue . Or you can use Document.prototype.validate() instead:

let model = new Model({a: true}); 
model.validate();

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