lch
lch

Reputation: 4931

How do I populate a field in a mongoose model?

var posting = new Posting({
  content: fields.content,
  creator: req.user,
});

posting.save(function(err) {
  if(err) {
    res.status(501).json({ error: err });
  } else {
    res.json({ posting: posting });
  }
});

The posting model has creator field which represents an instance of the User model. The Post instance is returned in JSON form after it has been saved. But the returned Post instance doesn't contain data from the corresponding User object in its creator field. It sends only the id value of the User instance.

How do I populate the creator field before sending the response?

Upvotes: 0

Views: 53

Answers (1)

gnerkus
gnerkus

Reputation: 12019

You need to call the .populate method of the Posting model on the posting instance:

posting.save(function(err) {
  if(err) {
    res.status(501).json({ error: err });
  } else {
    // Populate the 'posting' object's 'creator' field.
    Posting.populate(posting, { path: 'creator', model: 'User' }, function (err, posting) {
      res.json({ posting: posting });
    });
  }
});

Upvotes: 1

Related Questions