【问题标题】:MongoDB query documents created between now and two hours ago从现在到两小时前创建的 MongoDB 查询文档
【发布时间】:2016-02-10 13:40:12
【问题描述】:

我的节点中有一个 mongodb 查询,它根据几个条件找到一个文档:

Follow.find({
    user: req.user._id
    , followed: req.params.userId
}).populate(populateQuery).exec(function (err, results) {
    next.ifError(err);
    //res.send(results);
    if(results.length > 0){
        console.log('****** found!!!');
        console.log(results);
    }
});

所以这很好用。但是,我需要找到仅在现在和两个小时前之间创建的记录。 如何正确格式化查询对象中的日期对象?

{
    user: req.user._id
    , followed: req.params.userId
    ,dateCreated: {
        $gte: ISODate(<TWO HOURS AGO>),
        $lt: ISODate(<NOW>)
    }
}

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    创建两个日期对象,分别代表现在和2小时前的日期时间,如下:

    // Define
    var TWO_HOURS = 2*60*60*1000, // milliseconds
        now = new Date(),
        twoHoursAgoDate = new Date(now.getTime() - TWO_HOURS);
    
    Follow.find({
            user: req.user._id,
            followed: req.params.userId,
            dateCreated: { $gte: twoHoursAgoDate, $lt: now }
        }).populate(populateQuery).exec(function (err, results) {
            next.ifError(err);
            //res.send(results);
            if(results.length > 0){
                console.log('****** found!!!');
                console.log(results);
            }
        });
    

    更好的方法是使用 momentjs 库来简化日期时间操作,特别是您可以使用 subtract() 方法:

    // Define
    var now = moment(),
        twoHoursAgoDate = moment().subtract(2, 'hours');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 2017-03-15
      • 2015-09-02
      • 2015-07-12
      相关资源
      最近更新 更多