mosquito87
mosquito87

Reputation: 4440

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:

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

Upvotes: 0

Views: 476

Answers (2)

mosquito87
mosquito87

Reputation: 4440

This is how it worked for me:

ObjectSchema
    .where('handoverStartDate').gte(trip.startDate)
    .where('handoverEndDate').lte(trip.endDate)
    .where('handoverAddress.loc').near({
        center: {
            type: 'Point',
            coordinates: trip.address.loc
        },
        maxDistance: 10 * 1000
    });

Upvotes: 0

mrBorna
mrBorna

Reputation: 1777

You don't need the and. try

ObjectModel.find({
  handoverStartDate:    {$gte: trip.startDate},
  handoverEndDate:      {$lte: trip.endDate},
  'handoverAddress.loc': {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: trip.address.loc
      },
      $maxDistance: 10 * 1000
    }
})

Make sure trip is defined as a variable and that startDate,endDate, and address are all defined properties fitting your expectations.

Upvotes: 1

Related Questions