猫鼬 |填充后中间件以“保存”

时间:2021-02-17 14:57:08

标签: node.js mongodb mongoose

请考虑以下 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 的 post 中间件中访问父级的名称? 我正在尝试下面的代码,但 parent 被分配了 ObjectId 而不是实际的父模型。

childSchema.post("save", async function (child) {
    const parent = child.populate("parent").parent;
});

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我刚刚发现了 this.model("Model"),所以我要分享另一个解决方案。不过,不确定它与接受的相比如何:

childSchema.post("save", async function (child) {
    try {
        const parent = await this.model("Parent").findOne({ _id: child.parent });
        parent.children.push(child._id);
        parent.save();
    } catch (error) {}

});