Mongoose: How to add required validation when an other field has an specific value?

Created on 27 Mar 2017  路  8Comments  路  Source: Automattic/mongoose

I have a model that should have a field when there is an specific value for an other field (one-way dependency for two fields).

How this should be implemented in schema level validation?

Most helpful comment

new Schema({
  a: String,
  b: {
    type: String,
    required: function() { return this.a === 'test'; } // Only required if a equals 'test'
  }
});

All 8 comments

new Schema({
  a: String,
  b: {
    type: String,
    required: function() { return this.a === 'test'; } // Only required if a equals 'test'
  }
});

This could be fine if added to documentation.
And also this solution could be useful:

```javascript
new Schema({
a: String,
b: String
})

Schema.path('b').required(function() {
return this.a === 'test'
})

It's in the docs: http://mongoosejs.com/docs/api.html#schematype_SchemaType-required . But will add to guide as well

But when using async/await from some different modult this looses its context.

@vipulrawat i don't understand, can you please clarify what you mean?

new Schema({
  a: String,
  b: {
    type: String,
    required: function() { return this.a === 'test'; } // Only required if a equals 'test'
  }
});

@vkarpov15 How can I set error "message" here? If this.a is equal to 'test' but value for b is not provided, I want to set an error message to be thrown.

@Pradeep298 see docs

const s = new Schema({
  a: String,
  b: {
    type: String
  }
});

s.path('b').required(function() { return this.a === 'test'; }, 'your custom message here');

@vkarpov15 Thanks! I got this simpler way to do this. Need to add second parameter in required validation.

required: function() [{ return this.a === 'test'; }, 'YOUR CUSTOME MSG HERE']

Was this page helpful?
0 / 5 - 0 ratings