简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM