node.js - Pass data through to the view in Express -
i trying pass through result of query through view in express. query made using mongodb counts total points of collective users.
when try pass count through variable,
referenceerror: /sites/test/views/dashboard.ejs:76
which refers <%= totalpoints %> in ejs view. below code in app.js
app.get('/dashboard', function(req, res) { user.find({}, function(err, docs) { console.log(docs); }); user.find({ points: { $exists: true } }, function(err, docs) { var count = 0; (var = 0; < docs.length; i++) { count += docs[i].points; } return count; console.log('the total # of points is: ', count); }); var totalpoints = count; res.render('dashboard', { title: 'dashboard', user: req.user, totalpoints: totalpoints }); });
any ideas how can pass query result through?
node executes query asynchronously. is, the result of query not returned immediately. have wait untill result returned , callbacks used accomplish this.so, render page call has happen within callback. try modifying function this.
app.get('/dashboard', function(req, res) { user.find({}, function(err, docs) { console.log(docs); }); user.find({ points: { $exists: true } }, function(err, docs) { if(err){ console.log(err); //do error handling } //if no error, count , render var count = 0; (var = 0; < docs.length; i++) { count += docs[i].points; } var totalpoints = count; res.render('dashboard', { title: 'dashboard', user: req.user, totalpoints: totalpoints}); }); });
Comments
Post a Comment