NodeJS and mongoose - find records from last hour

巧了我就是萌 提交于 2019-12-11 01:30:52

问题


I am querying my MongoDB and I want to populate UI with 2 tables:

  1. all records from db
  2. current records, created within last hr

I am able to get all records, but the current record query below is not working.

app.get('/', function(req, res) {
    var myDate = new Date(Date.now() - 1 * 60 * 60 * 1000);

    var curr = MyCollection.find(
        {_id: { $gt : myDate }}
    ).exec();

    MyCollection.find({}, function(err, doc) {
        res.render('index.jade', {latest: curr, all: doc}); //this query
    });
});

I am doing { _id: { $gt : myDate }} but it does not return anything.

What am I doing wrong?


回答1:


From this post Popping Timestamps into ObjectIds, you need to convert the seconds from the timestamp to hexidecimal string first, something like the following:

var ObjectID = require('mongodb').ObjectID;
app.get('/', function(req, res) {
    var timestamp = new Date(Date.now() - 1 * 60 * 60 * 1000);
    var hexSeconds = Math.floor(timestamp/1000).toString(16);

    // Create an ObjectId with that hex timestamp
    var constructedObjectId = ObjectID(hexSeconds + "0000000000000000");
    console.log(constructedObjectId); // prints 564cd3810000000000000000
    MyCollection.find({}, function(err, doc) {
        MyCollection.find({
            "_id": { "$gt" : constructedObjectId }
        }, function (err, curr) {
            res.render('index.jade', { "latest": curr, "all": doc });
        });        
    });
});


来源:https://stackoverflow.com/questions/33788353/nodejs-and-mongoose-find-records-from-last-hour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!