Search code examples
node.jsmongodbmongoosemongoose-schema

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.


Solution

  • 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();