Reputation: 256
It seems that res.render is loading before data has been pulled from the mongodb. Is there anyway around this.
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');
});
As a side note i am using handlebars as well.
Upvotes: 0
Views: 878
Reputation: 644
As snozza mentions in his comment, the res.render
must be within the findOne callback.
This is due to Node.js and the fact that it is operating asynchronously. It runs both functions simultaneously, and doesn't wait for the data from MongoDB call to return. Within the findOne function itself, the code is run synchronously, therefore putting res.render
after your second if statement will solve the issue.
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');
}
});
});
Upvotes: 2