【问题标题】:NodeJS and mongoose - find records from last hourNodeJS 和 mongoose - 查找上一小时的记录
【发布时间】:2016-02-20 16:16:48
【问题描述】:

我正在查询我的 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 }},但它没有返回任何东西。

我做错了什么?

【问题讨论】:

    标签: node.js mongodb mongoose pug


    【解决方案1】:

    从这篇帖子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 });
            });        
        });
    });
    

    【讨论】:

    • 感谢您的快速响应。我试过了,但我得到了与 'doc' 相同的 'curr' 集合..
    • 如果您执行console.log(ObjectID.createFromTime(Date.now()*1000 - 24*60*60)) 并获取ObjectID,查询该ID 的集合,您会得到什么?
    • 啊……我明白了。它返回“0000000000000000000000000”。为什么它会返回全零?
    • 我的错,转换为毫秒而不是秒,这次再试一次。更多来自这篇文章Popping Timestamps into ObjectIds
    • 谢谢,我会读这篇文章.. 仍然得到零。不知道出了什么问题。
    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多