猫鼬:在保存时根据父字段值设置子文档字段值

编程入门 行业动态 更新时间:2024-10-19 04:24:06
本文介绍了猫鼬:在保存时根据父字段值设置子文档字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

几乎可以肯定在其他地方有介绍,但是:

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

更多推荐

猫鼬:在保存时根据父字段值设置子文档字段值

本文发布于:2023-11-22 13:32:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617609.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   文档   猫鼬

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!