node.js - Date query works in Mongo shell but not from Node
问题描述
When I run the following query from the Mongo shell, it works fine:
db.reports.find({
dateTime: {
$gte: "2018-06-12T05:00:00.000Z",
$lte: "2018-06-15T05:00:00.000Z",
}
}
gives the result:
{
"_id" : "5b3eaf388213fa2f5026ed26",
"report_id" : "1",
"description": "test description 1",
"address" : "300-BLK Hilliard Ave",
dateTime" : "2018-06-13T04:00:00.000Z"
},
{
"_id" : "5b3eaf388213fa2f5026ed27",
"report_id" : "2",
"description": "test description 2",
"address" : "1600-BLK Patton Ave",
dateTime" : "2018-06-13T04:00:00.000Z"
},
{
"_id" : "5b3eaf388213fa2f5026ed28",
"report_id" : "3",
"description": "test description 3",
"address" : " ",
dateTime" : "2018-06-14T04:00:00.000Z"
}
but when I try executing it in a Node script, it returns an empty array:
reportModel.find({
dateTime: {
$gte: "2018-06-12T05:00:00.000Z",
$lte: "2018-06-15T05:00:00.000Z",
}, (err, reports) => {
if (err) {
reject(err)
}
resolve(reports)
}
I know it is connecting to the database because the queries I run on other properties all return the expected values.
My report
model is:
const report = new mongoose.Schema({
report_id: { type: String, default: '' }
description: { type: String, default: '' }
address: { type: String, default: '' }
dateTime: { type: Date, default: Date.now }
})
I've tried various wrappings of new Date()
and new ISODate()
as suggested in various answers here to no avail. Any idea what could be going wrong?
解决方案
Mongoose 架构中的数据类型需要与保存的文档中的内容相匹配。因此,因为查询在 shell 中工作,所以您的dateTime
字段必须是文档中的字符串,并且您的架构定义应如下所示:
const report = new mongoose.Schema({
report_id: { type: String, default: '' }
description: { type: String, default: '' }
address: { type: String, default: '' }
dateTime: { type: String, default: Date.now }
})
但是,您可能需要考虑存储您的dateTime
值Date
以提高效率和灵活性。
推荐阅读
- php - Docker 对 PHPUnit 测试没有响应
- javafx-8 - Jfoenix JFXToggleButton 不提供开关外观
- javascript - 初始化 PouchDB 失败
- sql - 将日期时间转换为 UTC 开始时间 - Oracle db
- android - Android 内置电话计时器应用程序(时钟)在代码中的使用
- javascript - 在反应路由器路由路径道具中使用正则表达式
- angular - 角度前端中的 JSON
- python - 将 keras h5 转换为 tensorflow pb 以进行批量推理
- wheelnav.js - 如何使用wheelnav js沿路径弯曲navtitle
- javascript - 使用 javascript 捕获 html 标记值