I have been using this post as a guide in order to create some NodeJS code to connect to a MongoDB instance, authenticate, then calculate the difference between two timestamps, and then send this to a nunjucks template. My code is:
app.get('/test', function(req,res){
db.authenticate('USER', 'PASSWORD', function(err, result) {
assert.equal(true, result);
});
db.test('TEST').find({Total_items:{$exists:true}}).forEach(function(thing) {
var date1 = new Date(thing.DTG_posted_UTC);
var date2 = new Date(thing.read_dtg);
var dateDiff = date1.getTime() - date2.getTime();
var data = ({_id:thing._id,DTG_posted_UTC:thing.DTG_posted_UTC, read_dtg:thing.read_dtg ,dateDiff:dateDiff});
});
return res.render('test', data);
});
});
The Express server loads fine, but when I visit the 'test' page the app crashes, and returns: "ReferenceError: data1 is not defined".
I know the query is working, as I can log.console the results, and that works as expected (see below).
app.get('/test', function(req,res){
db.authenticate('USER', 'PASSWORD', function(err, result) {
assert.equal(true, result);
});
db.test('TEST').find({Total_items:{$exists:true}}).forEach(function(thing) {
var date1 = new Date(thing.DTG_posted_UTC);
var date2 = new Date(thing.read_dtg);
var dateDiff = date1.getTime() - date2.getTime();
var data = ({_id:thing._id,DTG_posted_UTC:thing.DTG_posted_UTC,read_dtg:thing.read_dtg ,dateDiff:dateDiff});
console.log(data);
});
return res.render('test');
});
Unfortuantly I cannot figure out how to pass the results of the Mongo query to my nunjucks template. Any help would be much appreciated.
Test
– ColSan Dec 05 '16 at 14:07