使用Mongoose + Express预先填充文档

我是Node + Mongoose的新手,目前正在使用KeystoneJS创buildAPI。 我已经设法填写作者的电子邮件和名称的所有职位。 我的问题是,有没有办法用作者每次填充post,可能有一些中间衣服,而不必在每一个检索post的方法中重写它? 我的目标是在整个代码中没有多个populate('author', 'email name')实例。 例如,将来我还想包括作者的个人资料照片url,而且我希望能够在一个位置进行更改,然后将反映在我检索post的每个地方。

当前实施:

 Post.model.find().populate('author', 'email name').exec(function (err, posts) { if (!err) { return res.json(posts); } else { return res.status(500).send("Error:<br><br>" + JSON.stringify(err)); } }); Post.model.findById(req.params.id).populate('author', 'email name').exec(function (err, post) { if(!err) { if (post) { return res.json(post); } else { return res.json({ error: 'Not found' }); } } else { return res.status(500).send("Error:<br><br>" + JSON.stringify(err)); } }); 

您可以使用静态模型创build模型。 这是模式方法的例子

 PostSchema.statics = { getAll: function(cb) { return this .find() .populate('author', 'email name') .exec(cb); } } 

你仍然应该使用“填充”,但它会在模式文件中,所以你将来不会在意​​它