Mongoose | populate on post middleware for "save"

Viewed 347

Please consider the following parentSchema and 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" },
});

How do I access the name of the parent within a post middleware of the childSchema? I am trying the code below but parent is assigned the ObjectId instead of the actual parent model.

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

What's the right way to do this?

2 Answers

If you want to populate something after the initial fetch you need to call execPopulate -- e.g.:

childSchema.post("save", async function (child) {
    try {
        if (!child.populated('parent')) {
            await child.populate('parent').execPopulate();
        }
        const parent = child.populate("parent").parent;
    } catch (err) {}
});

I just found out about this.model("Model") so I'm sharing another solution. Not sure how it compares with the accepted one, though:

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

});
Related