Mongoose 2dsphere not created and manual indexing works partially

400 views Asked by At

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

  1. Why userSchema.index({ location: "2dsphere" }); didnt create index in the first place?
  2. Why am I receiving only few records even when all lat and lng are same?
0

There are 0 answers