Node.js 使用Mongoose+预填充文档;快车
我是Node+Mongoose新手,目前正在使用KeystoneJS创建API。我已设法用作者的电子邮件和姓名填充所有帖子。我的问题是,有没有一种方法可以每次都用author来填充帖子,可能是用一些middlewear,而不必在我检索帖子的每个方法中重写它?我的目标是不让多个Node.js 使用Mongoose+预填充文档;快车,node.js,express,mongoose,keystone,Node.js,Express,Mongoose,Keystone,我是Node+Mongoose新手,目前正在使用KeystoneJS创建API。我已设法用作者的电子邮件和姓名填充所有帖子。我的问题是,有没有一种方法可以每次都用author来填充帖子,可能是用一些middlewear,而不必在我检索帖子的每个方法中重写它?我的目标是不让多个populate('author','email name')实例分散在整个代码中。例如,在将来,我还希望包括作者的个人资料照片url,我更希望能够在一个地方进行更改,这将反映在我检索帖子的每个地方 目前的执行情况: Pos
populate('author','email name')
实例分散在整个代码中。例如,在将来,我还希望包括作者的个人资料照片url,我更希望能够在一个地方进行更改,这将反映在我检索帖子的每个地方
目前的执行情况:
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));
}
});
Post.model.find().populate('author','email name').exec(函数(err,posts){
如果(!err){
return res.json(posts);
}否则{
返回res.status(500).send(“错误:
”+JSON.stringify(err));
}
});
Post.model.findById(req.params.id).populate('author','email name').exec(函数(err,Post){
如果(!err){
如果(员额){
返回res.json(post);
}否则{
返回res.json({error:'notfound'});
}
}否则{
返回res.status(500).send(“错误:
”+JSON.stringify(err));
}
});
您可以使用静力学创建模型。这是模式的方法示例
PostSchema.statics = {
getAll: function(cb) {
return this
.find()
.populate('author', 'email name')
.exec(cb);
}
}
您仍然应该使用“populate”,但它将在模式文件中,所以以后您将不再关心它