2014-04-30 51 views
2

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

当前实现:

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

回答

1

您可以使用模型。这是例子的架构方法

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

你还是应该用“填充”,但它会在架构文件,所以你不会在将来的

关心它