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

发布模型具有creator表示User模型实例的字段。实例保存后以PostJSON 形式返回。但是返回的实例在其字段Post中不包含来自相应User对象的数据。creator它只发送User实例的 id 值。

如何creator在发送响应之前填充该字段?

4

1 回答 1

1

您需要在实例上调用模型的.populate方法:Postingposting

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 });
    });
  }
});
于 2016-01-19T18:28:18.797 回答