Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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) {}
});
over 4 years ago · Santiago Trujillo Report

0

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

});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!