2016-01-19 48 views
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模型的一个实例。保存后,Post实例将以JSON形式返回。但是返回的Post实例不包含creator字段中对应的User对象的数据。它只发送User实例的id值。如何填充猫鼬模型中的字段?

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

+0

内部保存回调,尝试调用'User.populate(posting.creator)'之前返回结果。有关填充[这里](http://devdocs.io/mongoose/api#model_Model.populate)的更多细节。让我知道这是否有效,以便我可以回答你的问题。 – danilodeveloper

+0

没有工作。我也试过这个:User.populate(发帖,{path:'creator',model:'User'}); –

回答

1

你需要调用Posting模型.populate方法上posting实例:

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