node.js - 使用节点js检查mongo db中的条件字段datetime是否大于或等于currentdatetime
问题描述
我是 mongodb 的新手。我有一个名为conEnd
“2020-01-18T16:26:00.000+00:00”的日期字段。我需要检查一个条件,当前日期时间大于或等于日期时间conEnd
,取消订阅套接字。
这是我的代码。
const today = new Date();
today.setDate(today.getDate());
const date = (today.getDate() < 10) ? '0' + today.getDate() : today.getDate();
const month = (today.getMonth() < 10) ? '0' + (today.getMonth() + 1) : today.getMonth() + 1;
const currentDate = today.getFullYear() + '-' + month + '-' + date;
const hours = today.getHours();
const minutes = today.getMinutes();
const currentdatetime:any= '2021-01-18T16:26:00.000+00:00'//for testing I hard code the time. Otherwise I used currentDate+'T'+hours+':'+minutes+':00.000+00:00';
我在 mongodb 中有一个与当前时间匹配的字段。但是每当我使用下面的代码时,我都会得到空数组 []。
this.stockcontests.find({conEnd:currentdatetime},{conEnd:1}, function (err, result) {
if (err){
console.log(err)
}else{
console.log(result)
}
});
没有条件{conEnd : currentdatetime}
,上面的查询conEnd
以这种格式给我:
conEnd: 2020-01-18T16:26:00.000Z
我也尝试检查此条件但失败了{conEnd : {$gte : currentdatetime} }
如何正确执行条件,在哪里conEnd >= currentdatetime
?
解决方案
您应该使用 ISODate 来比较 MongoDB 中的日期:
"$gte" : new Date("2021-01-10T10:03:46Z")
ISODate 有效,因为这是您在数据库中的日期格式。
例子
db.getCollection('yourCollection').find({'sampleField': {$gte: new Date('2021-01-10T10:03:46.000Z')}})
您可以在此处查看更多详细信息:
推荐阅读
- javascript - 如何在插入数据时将多行选择的 id 传递到打印页面
- ruby - 我不明白这个从 base-256 转换为十进制的 ruby 代码
- java - Springboot缓存自动刷新redis和apache ignite
- python - 将字典中具有相同值的所有键组合起来,并将键与值交换,将值与键交换
- php - 如何在html表中显示数据库中的多条记录
- angular - ng-for 中的文本框仅在有数据时显示
- php - 如何使用此回调函数给出“电子邮件不存在”?
- python - 如何将一个句子字符串拆分成单词,还要让标点符号成为一个单独的元素
- java - Weblogic 正在提供战争文件,但未在部署列表中列出
- c# - 我无法找到正则表达式来查找“$i=0”而不是“$i==0”