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?
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']
Most helpful comment