简体   繁体   中英

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. 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.

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);
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM