Reputation: 333
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
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