Asif Akhtar
Asif Akhtar

Reputation: 333

find nearby users with respect to my coordinates within a radius of 10 miles in mongoose

I am facing the problem with the MongoDB Geospatial Queries with mongoose. i have a user document with the following schema. and i want all the users within 10 miles, eg: if my coordinate is [77.07361279999999, 28.4770304], then i want all the user within 10 miles of radius

i am following this documentation: link

const pointSchema = {
  PointType: {
    type: String,
    enum: ['Point'],
    required: true
  },
  coordinates: {
    type: [Number],
    required:true
  }
};

let userFields = {
  userName: {
    type: String,
    index: true,
    unique: true,
    required: true,
    lowercase: true,
  },
  gender: {
    type: String,
    enum: ['male', 'female']
  },
  currentLocation: {
    type: pointSchema,
    index: true,
    unique: true,
  }
};

let userSchema = new SCHEMA(Object.assign({}, userFields), { runSettersOnQuery: true });
let userModel = MONGOOSE.model('User', userSchema);

and my query is:

let recommendationList = userModel.find({
  currentLocation: {
    $nearSphere: {
      $geometry: {
        type: 'Point',
        coordinates: [77.07361279999999, 28.4770304],
      },
      $maxDistance: 10
    }
  }
});

Upvotes: 1

Views: 612

Answers (1)

Deeksha Sharma
Deeksha Sharma

Reputation: 3359

So after going through the documentation here properly, I finally figured out what you were doing wrong, there were few mistakes you were doing.

You need to change your schema to

const pointSchema = {
      type: {
        type: String,
        enum: ['Point'],
        required: true
      },
      coordinates: {
        type: [Number],
        required:true
      }
    };

and add ensureIndexes to your model

userModel.ensureIndexes({ 'currentLocation': '2dsphere' });

Lastly in your controllers you should query your model like this

let recommendationList = await userModel.aggregate([
      {
        $geoNear: {
          near: {
            type: 'Point',
            coordinates: userObj.currentLocation.coordinates
          },
          spherical: true,
          maxDistance: 10 * 1609.34,
          distanceMultiplier: 1,
          distanceField: 'distance',
          limit: 1,
          query : {
            gender: userObj.userPreference.datingPreferenceGender
          }
        }
      }
    ]);

Upvotes: 1

Related Questions