【问题标题】:Pre-populating documents using Mongoose + Express使用 Mongoose + Express 预填充文档
【发布时间】:2014-05-02 04:06:55
【问题描述】:

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

【问题讨论】:

    标签: node.js express mongoose keystone


    【解决方案1】:

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

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

    你仍然应该使用“填充”,但它会在模式文件中,所以你以后不会关心它

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 2017-09-25
      • 2014-08-06
      • 2017-01-27
      • 1970-01-01
      • 2016-06-18
      • 2014-08-16
      • 2019-01-08
      • 2017-03-21
      相关资源
      最近更新 更多