Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose | populate on post middleware for "save"

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?

like image 853
fmagno Avatar asked Sep 07 '25 10:09

fmagno


1 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) {}
});
like image 77
taxilian Avatar answered Sep 10 '25 08:09

taxilian