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

117
Views
El campo de esquema no se completa con mongoose populate

Aquí está mi modelo:

 const postSchema = Schema({ _id: Schema.Types.ObjectId, name: String, comments: Array }); const Post = mongoose.model(“Post”, postSchema); module.exports = Post;

Aquí está mi código haciendo una solicitud a otro microservicio para completar la matriz de comentarios, pero está vacío y no se está completando:

 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}`}); } });

¿Cuál es la mejor manera de hacer esto y hacer que llene el campo de comentarios?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  1. Te falta el atributo ref de la declaración del modelo:
 const postSchema = Schema({ _id: { type: Schema.Types.ObjectId, ref: 'comments' }, name: String, comments: Array }); const Post = mongoose.model(“Post”, postSchema); module.exports = Post;
  1. Debe llamar a exec después del método de populate .
 UserPost.findById(post._id).populate('comments').exec();
about 4 years ago · Juan Pablo Isaza 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!