node.js - 猫鼬 | 在 post 中间件上填充“保存”
问题描述
请考虑以下parentSchema
和childSchema
:
const parentSchema = new mongoose.Schema({
name: String,
children: [{ type: mongoose.Schema.Types.ObjectId, ref: "Child" }],
});
const childSchema = new mongoose.Schema({
name: String,
parent: { type: mongoose.Schema.Types.ObjectId, ref: "Parent" },
});
如何在 childSchema 的后中间件中访问父级的名称?我正在尝试下面的代码,但parent
分配了 ObjectId 而不是实际的父模型。
childSchema.post("save", async function (child) {
const parent = child.populate("parent").parent;
});
这样做的正确方法是什么?
解决方案
如果您想在初始获取后填充某些内容,您需要调用execPopulate
- 例如:
childSchema.post("save", async function (child) {
try {
if (!child.populated('parent')) {
await child.populate('parent').execPopulate();
}
const parent = child.populate("parent").parent;
} catch (err) {}
});
推荐阅读
- php - Laravel 8.x 错误命令模式:Linux 上的转储
- websphere - 修改用户供应的帐户请求失败,来自 IBM 的 500 错误
- ios - watchkit 独立苹果手表应用程序 - 每日本地通知未触发
- php - Laravel 5.8 Auth::guard()->check() 总是返回 false
- ios - 如何在没有 StoryBoards 的情况下以编程方式从 viewcontroller 转换到 TabbarController?
- python - 我对 Bellman-Ford 算法正确性的实现是错误的吗?
- ssis - SSIS 未将所有行从 ODBC(oracle)插入 SQL Server 2019
- reactjs - 如何在 React 中将 fontColor、fontBackgroundColor、fontSize 添加到 ckeditor5
- python - 如何在循环中从列表中删除值?pythoncrash课程书中的问题
- spartacus-storefront - 当具有无定价角色的用户登录“您无权执行此操作”时如何修复。在登陆页面中