本文介绍了猫鼬:在保存时根据父字段值设置子文档字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
几乎可以肯定在其他地方有介绍,但是:
This is almost certainly covered elsewhere, but:
如果我有一个带有嵌入式子文档的架构,例如:
If I have a single schema with an embedded sub-document, like so:
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?以下内容根本不起作用.
How would I save the name of the ParentSchema to ParentSchema.name and to ChildSchema.name in the same .save() action? The following does not work at all.
ChildSchema.pre('save', function(next){ this.name = ParentSchema.name; next(); });推荐答案
您可以通过将中间件移动到ParentSchema来进行访问,该中间件可以访问其自身及其子级:
You can do that by moving the middleware to ParentSchema which has access to itself and its children:
ParentSchema.pre('save', function(next){ var parent = this; this.child.forEach(function(child) { child.name = parent.name; }); next(); });更多推荐
猫鼬:在保存时根据父字段值设置子文档字段值
发布评论