【问题标题】:Cannot get collections by date with mongoose无法使用猫鼬按日期获取集合
【发布时间】:2020-01-11 07:35:00
【问题描述】:

我无法查询按日期过滤的集合

以下代码是我到目前为止的代码

//The following code shows how my schema is:

date: {type: Date, required: true}

//This is a date from a collection in MongoDB:
date: 2019-09-06T16:48:14.000+00:00

//This is how I saved the date in the MongoDB:
"2019/09/09 08:55:15"

//And this is how I perform the query in NodeJS:

let year = req.query.year;
let month = req.query.month;
let day = req.query.day;

let startDate = new Date(year, month, day);
let endDate = new Date(year, month, day);

// find documents in MongoDB
let query = SALES.find({ date: { $gte: startDate, $lte: endDate }});

// execute the query at a later time
query.exec(function (err, item) { // item is a dictionary
    if (err) return handleError(err); // throws an error if any
    if (item === null || item.length === 0) {
        res.json({
            status: 'empty',
        });
    }
    else {
        res.json({
            salesRecord: item
        });
     }
});

我读到这很容易得到,但我做不到。欢迎任何帮助????

我的查询没有错误,只是我得到的响应是空的。 预期的结果是从指定日期获取日期

【问题讨论】:

  • 你能出示你的req.query吗?
  • req.query 的值例如:年 = 2019、月 = 08、日 = 09 等
  • 您的startDateendDate 具有相同的值,因此您的数据库中的记录需要与new Date(year, month, day) 具有完全相同的日期
  • 是的,他们有,但查询不起作用;(

标签: javascript html node.js mongoose


【解决方案1】:

简答

您保存的日期(“2019/09/09 08:55:15”)被视为字符串。

试试这个:

db.mycollection.find({
    "date" : {"$gte": new Date()}
})

db.mycollection.find({
    "date" : {"$gte": ISODate(new Date())} // current date
});

说明

Mongodb shell 提供了多种返回日期的方法,可以是字符串,也可以是 Date 对象:

  1. Date() 方法以字符串形式返回当前日期。
  2. 使用 ISODate() 包装器返回 Date 对象的新 Date() 构造函数。
  3. ISODate() 构造函数,它使用 ISODate() 包装器返回一个 Date 对象。

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多