NodeJS 和 mongoose - 查找上一小时的记录

NodeJS and mongoose - find records from last hour

我正在查询我的 MongoDB,我想用 2 个表填充 UI:

  1. 来自数据库的所有记录
  2. 当前记录,在过去一小时内创建

我可以获取所有记录,但下面的当前记录查询不起作用。

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

我正在做 { _id: { $gt : myDate }} 但它没有 return 任何东西。

我做错了什么?

从这个post Popping Timestamps into ObjectIds开始,您需要先将秒数从时间戳转换为十六进制字符串,如下所示:

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