这几乎肯定在其他地方有所涉及,但是:
如果我有一个带有嵌入子文档的单一架构,如下所示:
var ChildSchema = new Schema ({
name : {
type: String,
trim: true
},
user :{
type: String,
trim: true
}
})
var ParentSchema = new Schema ({
name : {
type: String,
trim: true
},
child : [ChildSchema]
})
如何在同一个 .save() 操作中将 ParentSchema 的名称保存到 ParentSchema.name 和 ChildSchema.name?以下根本不起作用。
ChildSchema.pre('save', function(next){
this.name = ParentSchema.name;
next();
});
您可以通过将中间件移至ParentSchema
它可以访问自身及其子项:
ParentSchema.pre('save', function(next){
var parent = this;
this.child.forEach(function(child) {
child.name = parent.name;
});
next();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)