mercredi 25 février 2015

Complex query with mongoose, including subdocuments, near condition,

I have a very (at least for me) complex query using Mongoose.


First of all my schema:



var ObjectSchema = new Schema({
pickupStartDate: {type: Date, required: true, default: Date},
pickupEndDate: {type: Date, required: true, default: Date},

...

handoverStartDate: {type: Date, required: true, default: Date},
handoverEndDate: {type: Date, required: true, default: Date},

...
});


By using the "plugin mechanism" my Object has two addresses (called pickupAddress and handoverAddress. The address looks like that:



var name = 'address';

var obj = {};
obj[name] = {
street: String,
zipCode: String,
city: String,
state: String,
country: String,
loc: {type: [Number], index: '2dsphere'}
};
schema.add(obj);


And the other schema:



var TripSchema = new Schema({
startDate: {type: Date, required: true, default: Date},
endDate: {type: Date, required: true, default: Date},
handoverRadius: {type: Number, required: true}
});


It has an address, too (using plugin mechanism again).


I want the following query:


Find all "objects" which "fit" to my trip. "Fit" means:



  • handoverStartDate >= trip.startDate

  • handoverEndDate <= trip.endDate

  • `handoverAddress is near trip.address

  • ...


I thought this would be a good approach:



ObjectSchema
.find()
.and([
{ handoverStartDate: {$gte: trip.startDate}},
{ handoverEndDate: {$lte: trip.endDate}},
{ 'handoverAddress.loc': {$near: {
'$maxDistance': 10 * 1000,
'$center': {
type: 'Point',
coordinates: trip.address.loc
}
}}}
])
.exec(function(err, cdObjects) {
console.log(err);
console.log(cdObjects);
});


But this leads to the following error:


{ message: 'Cast to number failed for value "[object Object]" at path "handoverAddress.loc"'.


I guess because of 'handoverAddress.loc'. But I'm not sure how to specify that as it has to be a string (because it's a subdocument).


Aucun commentaire:

Enregistrer un commentaire