Mongodb/Express/Handlebars有res.render等待,直到数据被拉出
问题描述:
看起来res.render在从mongodb中拉出数据之前加载。有没有办法解决。Mongodb/Express/Handlebars有res.render等待,直到数据被拉出
app.use('/portfolio/:item_id', function(req, res, next) {
portfolioItem.findOne({ projectID : req.params.item_id}, function (err, item){
if (err) return handleError(err);
if (item) {
res.locals = {
script: ['isotope.js'],
title: item.projectTitle,
projectID: item.projectID,
projectTitle: item.projectTitle,
projectDescription: item.projectDescription,
projectURL: item.projectURL,
customerName: item.customerName,
websiteCategories: item.projectCategories,
grid: item.grid
}
}});
res.render('case_study');
});
作为一个侧面说明我也使用车把。
答
由于snozza在他的评论中提到,res.render
必须在findOne回调中。
这是由于Node.js和它异步操作的事实。它同时运行两个函数,并且不等待来自MongoDB调用的数据返回。在findOne函数本身中,代码是同步运行的,因此在第二个if语句将解决问题之后放置res.render
。
app.use('/portfolio/:item_id', function(req, res, next) {
portfolioItem.findOne({ projectID : req.params.item_id}, function (err, item){
if (err) return handleError(err);
if (item) {
res.locals = {
script: ['isotope.js'],
title: item.projectTitle,
projectID: item.projectID,
projectTitle: item.projectTitle,
projectDescription: item.projectDescription
projectURL: item.projectURL
customerName: item.customerName,
websiteCategories: item.projectCategories,
grid: item.grid
}
res.render('case_study');
}
});
});
res.render需要在findOne回调中 – snozza