首页 > 解决方案 > 猫鼬 | 在 post 中间件上填充“保存”

问题描述

请考虑以下parentSchemachildSchema

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

这样做的正确方法是什么?

标签: node.jsmongodbmongoose

解决方案


如果您想在初始获取后填充某些内容,您需要调用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) {}
});

推荐阅读