Transfer data before submission to Express

I am trying to pass the result of a query in my opinion to Express. The query is performed using mongodb, which counts the collective points of collective users.

When I try to pass the score through a variable, I get

ReferenceError: /Sites/test/views/dashboard.ejs:76 

which refers to <% = totalpoints%> in my ejs view. Below is my 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; for (var i = 0; i < 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 I can pass the result of the query through?

+5
source share
2 answers

Node executes the request asynchronously. That is, the query result is not returned immediately. You must wait until the result is returned and callbacks will be used to accomplish this. Thus, the callback call must occur in the callback. Try changing your function as follows.

 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, get the count and render it var count = 0; for (var i = 0; i < docs.length; i++) { count += docs[i].points; } var totalpoints = count; res.render('dashboard', { title: 'Dashboard', user: req.user, totalpoints: totalpoints}); }); }); 
+6
source

Node.js is asynchronous in nature, res.render will be executed before data is received from mongoose. Try the following code.

 app.get('/dashboard', function(req, res) { User.find({}, function(err, docs) { console.log(docs); }); User.aggregate({ $group: { _id: null, count: { $sum: "$points" } }}, function(err, docs) { if(err){ console.log(err); //do error handling } else res.render('dashboard', { title: 'Dashboard', user: req.user, totalpoints: docs.count }); } ); }); 
+1
source

All Articles