首页 > 解决方案 > 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?

标签: node.jsmongodbmongoose

解决方案


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 }
})

但是,您可能需要考虑存储您的dateTimeDate以提高效率和灵活性。


推荐阅读