猫鼬:MongoError没有地理搜索索引

时间:2018-06-19 02:09:26

标签: node.js mongodb mongoose

我正在使用Mongoose版本5.1.5,Mongodb版本3.0.10 当我使用mongoose Model.geoSearch方法时,它给出了一个错误,说明MongoError:没有geoSearch索引 下面是架构

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索引

因为它说没有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
    }
 ]

1 个答案:

答案 0 :(得分:1)

geoSearch函数需要使用geoHaystack索引,而不是2dSphere索引。我无法弄清楚如何使用猫鼬创建geoHaystack索引,但是您可以通过mongo shell创建索引。

https://docs.mongodb.com/manual/core/geohaystack/

如果您要在5.x中使用2dSphere索引进行地理查询,则可以使用find或{{进行常规的findOne$near查询1}}运算符。

https://docs.mongodb.com/v3.6/reference/operator/query/near/ https://docs.mongodb.com/v3.6/reference/operator/query/nearSphere/