I'm new to MongoDB and Mongoose. I'm trying to create a user model with location field indexed.
const userSchema = new mongoose.Schema({
/*...*/
location: {
type: { type: String },
coordinates: [Number],
},
/*...*/
});
userSchema.index({ location: "2dsphere" });
After schema definition, I tried adding 100 users with same lat,lng. Now, when I perform $geoNear it threw me error saying 'no geo indices for geoNear'. So, I manually created index for location field on users collection using MongoDB Compass. Then, when I try the following query,
User.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [lat, lng]
},
distanceField: "dist.calculated",
maxDistance: 2,
spherical: true
}
}]);
I receive only few records out of 100 records I had created. I'm unable to understand why all records isn't appearing even though the lat and lng are same.
My questions are as follows
- Why
userSchema.index({ location: "2dsphere" });didnt create index in the first place? - Why am I receiving only few records even when all lat and lng are same?