【发布时间】:2020-07-14 02:05:35
【问题描述】:
我正在使用 MongoDB 和 Mongoose。
假设我有以下架构。
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,
});
我希望我的“listingId”字段仅在“category”字段为“categoryA”时才需要。
此验证理想地存在于文档创建和更新期间。
如何构造自定义验证器来实现此效果?
编辑
我尝试了以下方法:
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);
}
},
},
});
但是,当我调用以下查询时:
Notification.findOneAndUpdate({}, $set: { category: "categoryA", meta: {} }).exec();
不抛出验证错误
【问题讨论】:
-
所以,您需要元属性。对吗?
-
我希望元属性中的“listing”字段是必需的
-
这能回答你的问题吗? Mongoose conditional required validation