我使用的是 Mongoose 5.1.5 版,Mongodb 3.0.10 版 当我使用 mongoose Model.geoSearch 方法时,它给我一个错误,说 MongoError: No geoSearch Index 下面是架构
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'
}
}
});
下面是geoSearch方法
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);
}
});
这是控制台中显示的内容 错误:MongoError:没有地理搜索索引
因为它说没有 geoSearch 索引,因此我添加了一个 2dsphere 索引,可以在模式中看到它。 请任何人都可以帮助我我做错了什么。
已更新 我在使用时得到以下信息
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
}
]
最佳答案
geoSearch 函数需要使用 geoHaystack
索引而不是 2dSphere 索引。我无法弄清楚如何使用 mongoose 创建 geoHaystack 索引,但您可以通过 mongo shell 创建索引。
https://docs.mongodb.com/manual/core/geohaystack/
如果您希望在 5.x 中使用 2dSphere 索引执行地理查询,您将使用 $near
或 $nearSphere
运算符在查询中。
https://docs.mongodb.com/v3.6/reference/operator/query/near/ https://docs.mongodb.com/v3.6/reference/operator/query/nearSphere/
关于node.js - Mongoose :MongoError 没有地理搜索索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50919725/