Node.js Mongoose:MongoError无地理搜索索引
我使用的是Mongoose版本5.1.5,Mongodb版本3.0.10 当我使用mongoose Model.geoSearch方法时,它会给我一个错误,说MongoError:No geoSearch Index 下面是模式Node.js Mongoose:MongoError无地理搜索索引,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我使用的是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, m
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索引,但您可以通过MongoShell创建索引
如果您希望在5.x中使用2dSphere索引进行地理查询,您将在查询中使用$near
或$nearSphere
操作符执行普通的find
或findOne
查询
您能从mongodb控制台运行以下命令吗?
db..getIndexes()
并检查索引是否已首先创建。我使用了您要求的内容,您可以查看已编辑的帖子。还有一件事,根据我的方案,我应该在geoSearch的第一个参数(即条件)中写些什么?有人知道吗?任何建议对我都很重要!!您可以选择我的答案或添加反馈,说明我的答案不正确的原因。非常感谢。