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

420
Views
'poblar' y trabajar con modelos padre/hijo en Mongoose/MongoDB

Tengo una configuración bastante simple en la que intento completar mis respuestas Mongoose JSON con todos los comentarios que pertenecen a una publicación.

Pensé que llamar a 'poblar' en la publicación devolvería todos los comentarios relacionados con la publicación, pero en cambio obtengo una matriz vacía. Simplemente no entiendo lo que estoy haciendo mal.

publicar.js

 const mongoose = require('mongoose'); const db = require('./init'); const postSchema = new mongoose.Schema({ title: String, url: String, body: String, votes: Number, _comments: [{type: mongoose.Schema.Types.ObjectId, ref: "Comment"}] }); const Post = mongoose.model('Post', postSchema); module.exports = Post;

comentario.js

 const mongoose = require('mongoose'); const db = require('./init'); const commentSchema = new mongoose.Schema({ // post_id: post_id, _post: { type: String, ref: 'Post'}, content: String, posted: { type: Date, default: Date.now() } }); const Comment = mongoose.model('Comment', commentSchema); module.exports = Comment;

publicaciones.js

 router.get('/', function(req, res, next) { // An empty find method will return all Posts Post.find() .populate('_comments') .then(posts => { res.json(posts) }) .catch(err => { res.json({ message: err.message }) }) });

y dentro del archivo posts.js configuré una ruta para crear un comentario cuando se envía una solicitud de publicación a posts/post_id/comments

 commentsRouter.post('/', function(req, res, next) { console.log(req.params.id) //res.json({response: 'hai'}) comment = new Comment; comment.content = req.body.content; comment._post = req.params.id comment.save((err) => { if (err) res.send(err); res.json({comment}); }); });

Los comentarios se crean cuando publico en esta ruta, y se crean con el valor de _post correcto, sin embargo, no se completan.

Por ejemplo, esta publicación se ha creado y no completa el comentario asociado a continuación:

 { "post": { "__v": 0, "votes": 0, "body": "Test Body", "url": "Test URL", "title": "Test Title", "_id": "587f4b0a4e8c5b2879c63a8c", "_comments": [] } } { "comment": { "__v": 0, "_post": "587f4b0a4e8c5b2879c63a8c", "content": "Test Comment Content", "_id": "587f4b6a4e8c5b2879c63a8d", "posted": "2017-01-18T10:37:55.935Z" } }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Cuando crea un comentario, también debe guardar la instancia de comentario _id en una publicación. Entonces, dentro de la devolución de llamada save() , puede hacer algo como

 commentsRouter.post('/', function(req, res, next) { console.log(req.params.id) //res.json({response: 'hai'}) comment = new Comment({ content: req.body.content; _post: req.params.id }); comment.save((err, doc) => { if (err) res.send(err); Post.findByIdAndUpdate(req.params.id, { $push: { _comments: doc._id } }, { new: true }, (err, post) => { if (err) res.send(err); res.json({doc}); } ) }); });
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!