mongodbmongoosemongodb-query

Mongoose geolocation + distance query


I am unsure how I recreate the following .find query into a Mongoose query:

db.places.find({
  loc: { $geoWithin: { $centerSphere: [[-74, 40.74], 100 / 3963.2] } }
});

I have set up the scheme

const AdScheme = new Schema({
  location: {
    coordinates: [{ 0: Number, 1: Number }]
  },
  type: String,
  name: String
});

export default mongoose.model("campaign", AdScheme);

but now I need to do a find query and this is not a simple .findOne().

How can I turn the above into a Mongoose query?


Solution

  • In mongoose docs it says mongoose has a helper method for $geoWithin.

    First, schema must be updated like this:

    const AdScheme = new Schema({
      location: {
        type: {
          type: String,
          default: 'Point',
          enum: ['Point']
        },
        coordinates: [Number]
      },
      type: String,
      name: String
    });
    

    And then query like this:

    AdModel.find().where('loc')
      .within({ center: [50,50], radius: 10, unique: true, spherical: true })
    

    Another option would be using mongoDB $geoNear aggregation.

    Then you can use it within mongoose like this:

    const geoNearOptions: {
      ... //todo
    }
    
    AdModel.aggregate([
      { $geoNear: geoNearOptions}
    ])