I'm just starting with Node, Express and Mongoose, and i need your help:
I have the following Mongoose query method inside my routes.js
app.get('/tournament-details/:_id', isLoggedIn, function(req, res){
var retrievedTournaments = null;
Tournament.find().exec(function(err, tournaments){
retrievedTournaments = tournaments;
});
//some other methods here
});
What i would like to do is to create a helper.js file, which would contain all sorts of Mongoose queries. These functions will replace the above one (and others), with just one call.
I'm using the below code in my helper.js file:
exports.retrieveAllTournaments = function retrieveAllTournaments(){
Tournament.find().exec(function(err, tournaments){
var queriedTournaments = tournaments;
return queriedTournaments;
});
}
However, when using:
res.render('tournament/tournament-details.ejs',{
tournaments: helperFunctions.retrieveAllTournaments()
}
i receive the following error:
Cannot call method 'forEach' of undefined at eval
Any help is much appreciated. Thank you!
It's an asynchronous function, you can only return the value in a callback.
Helper.js
exports.retrieveAllTournaments = function(cb){
Tournament.find().exec(function(err, tournaments){
cb(tournaments);
});
}
inside the route
helperFunctions.retrieveAllTournaments(function(tournaments) {
res.render('tournament/tournament-details.ejs', {
tournaments: tournaments
});
});