且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

猫鼬日期过滤器

更新时间:2023-10-25 23:41:10

使用实际的日期对象进行查询,而不是像您目前所做的那样使用字符串.因为 mongo 存储用 ISODate 包裹的日期 助手和底层 BSON(mongo 本地使用的存储数据格式)有一个专用的日期类型 UTC 日期时间,它是一个 64 位(因此,8 字节)有符号整数,表示自 Unix 时间纪元以来的毫秒数,您的查询不会返回任何内容,因为它会将 mongo 中的日期字段与 ISO 格式的字符串进行比较.

Use the actual date object for your query, not string as you are doing presently. Because mongo stores dates wrapped with the ISODate helper and the underlying BSON (the storage data format used by mongo natively) has a dedicated date type UTC datetime which is a 64 bit (so, 8 byte) signed integer denoting milliseconds since Unix time epoch, your query doesn't return anything as it will be comparing the date fields in mongo with an ISO formatted string.

因此,删除 toISOString() 转换并使用日期对象:

So, drop the toISOString() conversion and use the date object:

if (data.date) {
    const date = new Date();
    const dateRange = data.date.slice(0, -1); // strip the "d" from "7d"
    date.setDate(date.getDate() - dateRange);
    query.start = { $lte: date };
    console.log(query);
}

Call.find(query, function (error, docs) {
    if (error) callback(error, null);
    callback(null, docs);    
});

更好的是,您可以使用 momentjs 插件,它具有非常直观和简单的日期时间操作 API.您可以使用的一种方法是 subtract() 函数获取日期对象 n 天前:


Better yet, you can use the momentjs plugin that has a very intuitive and easy datetime manipluation API. One method you can use is the subtract() function to get the date object n number of days ago:

if (data.date) {    
    const dateRange = data.date.slice(0, -1); // strip the "d" from "7d"
    const date = moment().subtract(dateRange, "days");
    query.start = { $lte: date };
    console.log(query);
}

Call.find(query, function (error, docs) {
    if (error) callback(error, null);
    callback(null, docs);    
});