Reputation: 42627
This isn't quite a "sometimes required" field, but a little different.
I need to have a field in a Mongoose document that, depending on other data in the document, must NEVER be populated.
Is there a way to define the schema such that if field a
is populated, that field b
MUST be null?
I would strongly prefer to NOT solve this with mongoose hooks...
Upvotes: 0
Views: 226
Reputation: 314
It can be done using custom validators, this example is for mongoose version 5.x.
new Schema({
a: {
type: String
},
b: {
type: String,
default: null,
validate: {
validator: function (v) {
if (this.a && v === null) {
return true
}
return false
},
message: (props) => `${props.value} should be null!`
}
}
})
Upvotes: 1