title: Mongoose conditional required field
body: <p>The schema should be defined, so that an attribute <code>b</code> is required iff the attribute <code>a</code> is set to false.</p>
  <pre><code>const { Schema, model } = require(&quot;mongoose&quot;);
  
  const schema = new Schema({
    a: { type: Boolean, default: false },
    b: {
      type: Number,
      required: function () {
        return !this.a;
      }
    }
  });
  
  const Model = model(&quot;bla&quot;, schema);
  
  Model.validate({a: true});
  </code></pre>
  <p>But if I define the schema as above, the validate call in the last line will throw an error that <code>b</code> is required, even if <code>a</code> is set to <code>false</code>:</p>
  <pre><code>ValidationError: Validation failed: b: Path `b` is required.
  </code></pre>
  <p>The problem thems to be, that this is not referring to the schema, but to the function and there is no value <code>a</code> defined, so the function will only evaluate to <code>true</code> and b is always required.</p>