Reputation: 7623
I am using MongoDB and Mongoose.
Suppose I have the following Schema.
const notificationMetaSchema = new mongoose.Schema({
listingId: { type: mongoose.Schema.Types.ObjectId },
});
const notificationSchema = new mongoose.Schema({
category: { type: String, required: true, enum: [ "categoryA", "categoryB" ] },
meta: notificationMetaSchema,
});
I want my "listingId" field to be required only when the "category" field is "categoryA".
This validation ideally exists during both document creation and updates.
How do I construct a custom validator to achieve this effect?
EDIT
I have tried the following:
const notificationSchema = new mongoose.Schema({
category: { type: String, required: true, enum: [ "categoryA", "categoryB" ] },
meta: {
listingId: {
type: mongoose.Schema.Types.ObjectId,
required: function () {
return [
"categoryA",
].includes(this.category);
}
},
},
});
However, when I call the following query:
Notification.findOneAndUpdate({}, $set: { category: "categoryA", meta: {} }).exec();
No validation error is thrown
Upvotes: 0
Views: 283
Reputation: 17915
You can write a javaScript function for a field in mongoose schema, that function can act as custom validator, Your schema should look like :
const notificationSchema = new mongoose.Schema({
category: {
type: String,
required: true,
enum: ["categoryA", "categoryB"]
},
meta: {
listingId: {
type: mongoose.Schema.Types.ObjectId,
required: function checkRequiredOrNot() {
/** This function returns true or false, 'this.category' will retrieve current object's 'category' value */
return this.category == "categoryA" ? true : false;
}
}
}
});
Upvotes: 1