简体   繁体   中英

Mongoose query within the same schema

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM