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.
The location will be stored like below in mongoDB.
So just check your definition of location again.
typevalue is fixed to "point" here always, try to model that as static value. And the index you have specified should be onlocationnot insidetype.You can check from DB if there is a index created by this query
If not then there is problem with index creation. I got below code from https://mongoosejs.com/docs/api.html#schematype_SchemaType-index