I am attempting to store and query locations based on coordinate points with Mongoose 5.3.8 in order to return points within the radius of another point. I have read the docs and have implemented the pointSchema + citySchema example in the section: Using GeoJSON data seen below
const pointSchema = new mongoose.Schema({
type: {
type: String,
enum: ['Point'],
required: true
},
coordinates: {
type: [Number],
required: true
}
});
const citySchema = new mongoose.Schema({
name: String,
location: {
type: pointSchema,
required: true
}
});
with an express endpoint, I query an mLab instance with the following code and a document stored as:
DOCUMENT ---------------------------
{
"_id": "5bdbeb78949541086880dd35",
"name": "Location1",
"location": {
"coordinates": [
48.5,
-123.8
],
"_id": "5bdbeb78949541086880dd36",
"type": "Point"
}
}
QUERY --------------------------------
Location.findOne({
location: {
$near: {
$geometry: {
type: "Point" ,
coordinates: coordinates // [long, latt]
},
$maxDistance: 10000,
$minDistance: 1
}
}
}).then(res => console.log(res))
.catch(err => console.log(err))
The above query caught the error:
planner returned error: unable to find index for $geoNear query
I attempted to add an index on the LocationSchema by calling .index()
LocationSchema.index({ "location": "2dsphere" });
I also attempted to add an index to the Schema by:
LocationSchema.index({ category: 1, location: "2dsphere" });
no index was created on the schema and the error persisted.
I have attempted several other Schema/Query combinations including:
- Mongoose geospatial search: distance not working - Feb 7, 2016
- Mongoose Geospatial Queries with $near - April 10, 2018
- unable to find index for $geoNear query #6549 - May 31, 2018
- Net Ninja's GeoJSON tutorial - March 27, 2017
I have gotten none of them to return points within the radius of another point despite using nearby coordinates to query. I don't understand where this is going wrong.
- Is there a working example of a geospatial query that can return points within the radius of another point in mongoose 5.3.8?
edit: clarified question
EDIT:
Got it to work. In the mongoose options connecting to the mLab instance my options were as followed:
const mongoOptions = {
useCreateIndex: true,
useNewUrlParser: true,
autoIndex: false,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 500,
poolSize: 10,
bufferMaxEntries: 0
};
The autoIndex: false
parameter made it so that no new indexes could be created, even when specifying LocationSchema.index({ "location": "2dsphere" });
.
To fix this I had to add LocationSchema.options.autoIndex = true;
for some reason. Hope this might help someone.