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

115
Vistas
Schema field is not being populated using mongoose populate

Here is my model:

const postSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  comments: Array
});

const Post = mongoose.model(“Post”, postSchema);
module.exports = Post;

Here is my code making a request to another microservice to populate the comments array, but it is empty, and is not being populated:

const UserPost = require(“./PostSchema”);

router.get("/post/list", async (request, response) =>{

try {
    let myUserPost = await UserPost.find();



    let postComments = await Promise.all(
        myUserPost.map((post) =>{
            
            axios.get(`${process.env.COMMENTS_MICROSERVICE_URL}/router/comments/list/comments/by/post/${post._id}`)
   .then((resp) => {
         resp.data.message.map((comment) =>{
    
                    
                    if(String(post._id) === comment.postID){
                        //console.log("post._id: ", post._id);

 /*** Desired, but does not work
    return UserPost.findById(post._id).populate('comments').exec();  */

 //The following alternative (embedding) works but adds the data to array
/***return UserPost.findByIdAndUpdate(post._id, {$addToSet: {"comments": comment}}, (err, data) =>{
err ? console.log(err) : console.log("aa: ", data);
     });   */  
                    }else{
                        console.log("no")
    
                    }
                    
                });
            })
            
        })
    );  

        
             

    return response.status(200).json({message: myUserPost});
}catch(err){
    return response.status(400).json({message: `${err}`});
}
});

What’s the best way to go about this and have it populate the comments field?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. You are missing the ref attribute from the model declaration:
const postSchema = Schema({
    _id: {
        type: Schema.Types.ObjectId,
        ref: 'comments'
    },
    name: String,
    comments: Array
  });
  
  const Post = mongoose.model(“Post”, postSchema);
  module.exports = Post;
  1. You should call exec after the populate method.
UserPost.findById(post._id).populate('comments').exec();
about 4 years ago · Juan Pablo Isaza 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