【问题标题】:Check condition field datetime is greater than or equal to currentdatetime in mongo db using node js使用节点js检查条件字段日期时间是否大于或等于mongodb中的当前日期时间
【发布时间】:2021-04-22 16:23:45
【问题描述】:

我是 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 &gt;= currentdatetime

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    您应该使用 ISODate 来比较 MongoDB 中的日期:

    "$gte" : new Date("2021-01-10T10:03:46Z")
    

    ISODate 有效,因为这是您在 DB 中的日期格式。

    例子

    db.getCollection('yourCollection').find({'sampleField': {$gte: new Date('2021-01-10T10:03:46.000Z')}})
    

    您可以在此处查看更多详细信息:

    https://docs.mongodb.com/manual/core/shell-types/

    【讨论】:

    • 但它说找不到 ISODate。
    • ISODate 是 MongoDB 的一部分,在您的情况下不可用。相反,您应该使用 Date 对象,而 MongoDB 驱动程序(例如,您当前使用的 Mongoose ORM)将在幕后处理 Date 和 ISODate 之间的类型转换。我已经更新了上面的代码
    • 使用 Date()。谢谢你:-)。
    猜你喜欢
    • 2013-06-25
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    相关资源
    最近更新 更多