2

我是 Node+Mongoose 的新手,目前正在使用 KeystoneJS 创建 API。我已经设法用作者的电子邮件和姓名填充所有帖子。我的问题是,有没有办法每次都用作者填充帖子,可能还有一些中间件,而不必在我检索帖子的每种方法中重写它?我的目标是不要populate('author', 'email name')在整个代码中分散多个实例。例如,将来,我还想包含作者的个人资料照片网址,并且我希望能够在一个地方进行更改,然后将反映在我检索帖子的每个地方.

当前实施:

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

1 回答 1

1

您可以使用statics创建模型。这是模式方法的示例

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

您仍然应该使用“填充”,但它将在模式文件中,因此您将来不会关心它

于 2014-04-30T03:07:31.060 回答