crash springfield
crash springfield

Reputation: 1082

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?

Upvotes: 0

Views: 169

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

The data types in your Mongoose schema needs to match what's in the saved documents. So because the query works in the shell, your dateTime field must be a string in your documents, and your schema definition should look like:

const report = new mongoose.Schema({
  report_id: { type: String, default: '' }
  description: { type: String, default: '' }      
  address: { type: String, default: '' }
  dateTime: { type: String, default: Date.now }
})

However, you may want to consider storing your dateTime values as Date for better efficiency and flexibility.

Upvotes: 1

Related Questions