Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

311
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda