0

This is my Schema

    const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    skills: [{
        type: String
    }],
    location: {
        type: {
            type: String,
            index: '2dsphere'
        },

        coordinates: []
    }
});

And my query looks something like this

    User.find({
    location: {
        $nearSphere: {
            $geometry: {
                type: "Point",
                coordinates: [77.032448, 28.590654]
            },
            $maxDistance: 2000
        }
    }
   }).find((error, results) => {
    if (error) console.log(error);
    console.log(results);
   });

Whenever I run the code, I am getting this error

    ok: 0,
  errmsg:
   'error processing query: ns=StudyJamm.usersTree: GEONEAR  field=location maxdist=2000 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
  code: 2,
  codeName: 'BadValue',
  name: 'MongoError',
  [Symbol(mongoErrorContextSymbol)]: {}

PS:- I already tried User.index({location: "2dsphere"});

What am I doing wrong here? I have gone through all the similar questions on Stack Overflow, but no solution works for me.

1 Answers1

0

The location will be stored like below in mongoDB.

location: {
      type: "Point",
      coordinates: [-73.856077, 40.848447]
}

So just check your definition of location again. type value is fixed to "point" here always, try to model that as static value. And the index you have specified should be on location not inside type.

You can check from DB if there is a index created by this query

db.getCollection('data').getIndexes()

If not then there is problem with index creation. I got below code from https://mongoosejs.com/docs/api.html#schematype_SchemaType-index

var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
Lucia
  • 791
  • 1
  • 8
  • 17