0

Is it possible to perform a query within the same schema? For example, If I have a schema which has 2 date fields, and I need to find the data where one Date field is greater than the other. This is my schema and code sample.

var Schema = mongoose.Schema;

var someSchema = new Schema({
   someId          :  { type: String, default: '' ,index:true, unique: true  },
   userName   :  { type: String, default: ''},
   fullName   :  { type: String, default: '' },
   created      :   {type: Date, default:''},
   lastUpdated     :   {type: Date, default:''},
   primaryGroupId  :   {type:String,default:''},
   nextHearing     :   {type: Date, default:''},
   status   :  {type:String,default:'open'},
   
});



mongoose.model('Problem', someSchema);

The below code is my query.

var problemModel = mongoose.model('Problem');

var today = Date.now();

problemModel.find({$and:[{'nextHearing':{$lte: today}},{'nextHearing':{$gte : 'lastUpdated'}}]},function(err, result){

When I run the program, I get the following error

{ message: 'Cast to date failed for value "lastUpdated" at path "nextHearing"', name: 'CastError', type: 'date', value: 'lastUpdated', path: 'nextHearing' }

1 Answers1

0

new Date() returns the current date as a Date object. The mongo shell wraps the Date object with the ISODate helper. The ISODate is in UTC.

so you may need to change:

var today = Date.now();

to

var today = new Date().toISOString();

Also, take a look at this

Community
  • 1
  • 1
Tareq
  • 5,283
  • 2
  • 15
  • 18
  • I don't think that's the issue. I tried using your code as well. The error is with this `{'nextHearing':{$gte : 'lastUpdated'}}` – flatbreadcandycane Feb 04 '17 at 13:20
  • both `nextHearing` and `lastUpdated` are fields of the same schema, is it possible to compare them the way I have done? If not, what's the possible solution? – flatbreadcandycane Feb 04 '17 at 13:22