[英]Calculate the difference between two times from MongoDB in NodeJS and send to nunjucks
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. 我一直以此帖子为指导,以创建一些NodeJS代码以连接到MongoDB实例,进行身份验证,然后计算两个时间戳之间的差异,然后将其发送到nunjucks模板。 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". Express服务器加载正常,但是当我访问“测试”页面时,应用程序崩溃,并返回:“ ReferenceError:未定义data1”。
I know the query is working, as I can log.console the results, and that works as expected (see below). 我知道查询正在工作,因为我可以log.console结果,并且按预期工作(见下文)。
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. 不幸的是,我无法弄清楚如何将Mongo查询的结果传递给我的nunjucks模板。 Any help would be much appreciated.
任何帮助将非常感激。
app.get('/test', function(req, res, next){
db.authenticate('USER', 'PASSWORD', function (err, result) {
assert.equal(true, result);
// if (err)
// return next(err);
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
};
res.render('test', data);
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.