我想在子文档中实现一些验证逻辑,该验证与父文档字段的状态有关。我的代码如下:
const childSchema = function (parent) {
return new Schema({
name: {
type: String,
set: function (v) {
const prefix = (parent.isFlashed) ? 'with' : 'without'
return `${prefix} ${v}`
}
},
version: String
})
}
const parentSchema = new Schema({
isFlashed: Boolean,
firmware: childSchema(this)
})
我想知道为什么我的代码不起作用以及如何检查子模式中父模式的属性值。
预先感谢
答案 0 :(得分:0)
您无需将子架构定义为返回新Schema
的函数。您只需在父级中引用子级架构即可。
const ChildSchema = new Schema({
name: {
type: String,
set: function(v) {
const prefix = this.parent().isFlashed ? 'with' : 'without';
return `${prefix} ${v}`;
}
}
});
const ParentSchema = new Schema({
isFlashed: Boolean,
firmware: ChildSchema
});
您会注意到,我根据this
:this.parent()
引用父对象。
在创建带有子对象的新父对象时,只需使用与子模式格式匹配的嵌套对象即可。
const Parent = mongoose.model('Parent', ParentSchema);
const parent = new Parent({isFlashed: false, firmware: {name: "ChildName"}});