我的节点中有一个 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>)
}
}
最佳答案
创建两个日期对象,分别表示现在和 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');
关于MongoDB 查询从现在到两小时前创建的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35316842/