I have an application where I need to read from two different collections in my Mongo database and pass both the returned objects into a handlebars template.
With the code I have below I can't figure out how to get it to work, as the universityData and courseData variables aren't getting populated, not sure if this is the right way to do it anyway.
The university and course objects in the callbacks are working correctly as when I log I get the values I need.
router.get('/newcastle/G400', function(req, res) {
var db = req.db;
var universityData;
var courseData;
db.collection('universities', function(err, collection) {
collection.findOne({'code': 'N21'}, function(err, university) {
universityData = university;
console.log(university);
//res.render('course', {title: university.name, university: university, course: { "code": "G400", "name": "Computer Science", "studylength": "3 years (BSc)/4 years (MSc)", "requirements": "AAB - ABB", "satisfactionrating": "98"}});
});
});
db.collection('courses', function(err, collection) {
collection.findOne({'universitycode': 'N21', 'code': 'G400'}, function(err, course) {
courseData = course;
console.log(course);
});
});
console.log(universityData);
console.log(courseData);
res.render('course', {university: universityData, course: courseData});
});
My question is how can I get the objects from each of the queries to be passed into one template?
Any help would be appreciated as I'm fairly new to Javascript, node and Mongo.
Even though it's just "two" functions, you could use a module like async
to help organize them without deeply nesting. Example:
var async = require('async');
// ...
router.get('/newcastle/G400', function(req, res) {
var db = req.db;
async.parallel([
universityData: function(callback) {
db.collection('universities', function(err, collection) {
if (err)
return callback(err);
collection.findOne({'code': 'N21'}, callback);
});
},
courseData: function(callback) {
db.collection('courses', function(err, collection) {
if (err)
return callback(err);
collection.findOne({'universitycode': 'N21', 'code': 'G400'}, callback);
});
}
], function(err, results) {
if (err)
return res.send(500);
// results === { universityData: { ... }, courseData: { ... } }
res.render('course', results);
});
});