地理位置:无法在nodejs中找到$ geoNear查询的索引

时间:2017-06-28 05:07:25

标签: node.js mongoose geolocation

我想使用LatLong在地理位置附近找到,这是我的代码:

var locationSchema = new Schema({

name : {
    required : "Name is required",
    type     : String
},

address : {
    required : "address is required",
    type     : [Number],
    index    : '2d'
},

createdAt : {
    type : Date,
    default : new Date()
}
});

module.exports = mongoose.model('Location', locationSchema);

现在我收集了数据,我想获取所有提供Latm的3公里范围的文档。

以下是我获取数据的控制器代码:

myLocation : function (req, res) {
var coords = [],
        maxDistance = 3;

    coords[0] = parseFloat(req.query.longitude);
    coords[1] = parseFloat(req.query.latitude);
    maxDistance /= 6371; // divide by this number as earth's approximate radius is 6371 KMs.
Location.find({
            location : {
                $near           : coords,
                $maxDistance    : maxDistance
            }
        }, function (err, locations) {
            if (err) {
                res.send(err);
            } else {
                console.log("Location list");
                res.send(locations);
            }
        });

{ MongoError: error processing query: ns=geolocation.locationTree: GEONEAR  field=location maxdist=0.000470884 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error: unable to find index for $geoNear query
    at Function.MongoError.create (/var/www/NodeJS/GeoLocation/node_modules/mongodb-core/lib/error.js:31:11)
    at queryCallback (/var/www/NodeJS/GeoLocation/node_modules/mongodb-core/lib/cursor.js:212:36)
    at /var/www/NodeJS/GeoLocation/node_modules/mongodb-core/lib/connection/pool.js:469:18
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  name: 'MongoError',
  message: 'error processing query: ns=geolocation.locationTree: GEONEAR  field=location maxdist=0.000470884 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
  ok: 0,
  errmsg: 'error processing query: ns=geolocation.locationTree: GEONEAR  field=location maxdist=0.000470884 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
  code: 2,
  codeName: 'BadValue' }

2 个答案:

答案 0 :(得分:1)

Location.find({
            address: {
                $near: {
                    $geometry : {
                        type: 'Point',
                        coordinates: coords
                    },
                    $maxDistance    : maxDistance * 1000
                }
            }
        }, function (err, locations) {
           console.log(locations);
        });

答案 1 :(得分:0)

  

无法找到$ geoNear查询的索引

db.collectionName.createIndex({ "location": "2d" })

参考:Create a 2d Index