Reputation: 76
I am using Mongoose version 5.1.5, Mongodb version 3.0.10 When I use mongoose Model.geoSearch method, it gives me an error saying MongoError: No geoSearch Index Below is the schema
var hotelSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
stars: {
type: Number,
min: 0,
max: 5,
"default": 0
},
services: [String],
description: String,
photos: [String],
currency : String,
reviews : [reviewSchema],
rooms : [roomSchema],
location : {
address : String,
// Always store coordinates longitude (East/West), latitude (North/South)
order.
coordinates : {
type : [Number],
index: '2dsphere'
}
}
});
Below is the geoSearch method
var geoOptions = {
near: [lng,lat],
maxDistance: 2000,
limit: 5
}
Hotel
.geoSearch({coordinates: '2dsphere'}, geoOptions, function(err, results, stats){
if(err){
console.log('Error: '+err);
res
.json(err);
} else{
console.log("Geo Results " + results);
console.log("Geo Stats "+ stats);
res
.status(200)
.json(results);
}
});
And here is what appears in the console Error: MongoError: no geoSearch index
As it says there is no geoSearch index thus I have added a 2dsphere index which can be seen in the schema. Please can anyone help me what I am doing wrong.
Updated I get the following when I use
db.hotels.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "meanhotel.hotels"
},
{
"v" : 2,
"key" : {
"location.coordinates" : "2dsphere"
},
"name" : "location.coordinates_2dsphere",
"ns" : "meanhotel.hotels",
"background" : true,
"2dsphereIndexVersion" : 3
},
{
"v" : 2,
"key" : {
"location" : 1
},
"name" : "location_1",
"ns" : "meanhotel.hotels",
"background" : true
},
{
"v" : 2,
"key" : {
"coordinates" : 1
},
"name" : "coordinates_1",
"ns" : "meanhotel.hotels",
"background" : true
},
{
"v" : 2,
"key" : {
"coordinates" : "2dsphere"
},
"name" : "coordinates_2dsphere",
"ns" : "meanhotel.hotels",
"background" : true,
"2dsphereIndexVersion" : 3
}
]
Upvotes: 1
Views: 815
Reputation: 4591
The geoSearch function requires the use of a geoHaystack
index and not a 2dSphere index. I was unable to figure out how to create the geoHaystack index using mongoose but you can create the index via the mongo shell.
https://docs.mongodb.com/manual/core/geohaystack/
If you're looking to do a geo query in 5.x that uses a 2dSphere index, you'll do a normal find
or findOne
query with $near
or $nearSphere
operator in the query.
https://docs.mongodb.com/v3.6/reference/operator/query/near/ https://docs.mongodb.com/v3.6/reference/operator/query/nearSphere/
Upvotes: 1