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

424
Views
'populate' and working with parent / child models in Mongoose / MongoDB

I have a pretty simple setup where I'm trying to populate my Mongoose JSON responses with all Comments that belong to a Post

I thought that calling 'populate' on Post would return all comments related to the Post, but instead I'm getting an empty array. I just don't get what I'm doing wrong.

post.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;

comment.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;

posts.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 })
  })
});

and within the posts.js file I've set up a route to create a comment when a post request is sent to 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});
    });
});

Comments are being created when I post to this route, and they are created with the correct _post value, however populate isn't picking them up.

For example, this post has been created, and it doesn't populate the associated comment below:

{
  "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

When you create a comment, you also have to save the comment instance _id to a post. So within the save() callback, you can do something like

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!