【问题标题】:Mongoose: Set subdocument field value based on parent field value on saveMongoose:在保存时根据父字段值设置子文档字段值
【发布时间】:2014-09-13 17:54:52
【问题描述】:

这几乎肯定会在其他地方有所提及,但是:

如果我有一个带有嵌入式子文档的架构,如下所示:

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();
});

【问题讨论】:

  • 你是如何连接父母和孩子的?
  • 还可以查看Mongoose Sub Docs 示例。
  • 已编辑以显示子架构在父架构中被调用和创建。仍在寻找答案。

标签: node.js mongodb mongoose


【解决方案1】:

您可以通过将中间件移动到可以访问自身及其子级的ParentSchema 来做到这一点:

ParentSchema.pre('save', function(next){
    var parent = this;
    this.child.forEach(function(child) {
        child.name = parent.name;
    });
    next();
});

【讨论】:

  • this 对我来说是undefinedTypeError: Cannot read property 'forEach' of undefined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 2020-01-03
  • 2017-07-11
相关资源
最近更新 更多