使用mongoose / mongodb搜索点附近的所有多边形时失败

时间:2015-06-02 08:07:55

标签: node.js mongodb mongoose geospatial geojson

我正在尝试搜索距离点距离的点数x公里的任何GeoJSON多边形。重要的是它是GeoJSON多边形而不是GeoJSON点。

我有以下但是我收到错误:

  

'无法执行查询:错误处理查询:ns = geoPolygonExample.areas limit = 1000 skip = 0 \ nTree:GEONEAR field = loc.coordinates maxdist = 0.0156961 isNearSphere = 1 \ nSort:{} \ nProj: {} \ n planner返回错误:无法找到$ geoNear查询'

的索引

我已经检查过我的索引是否正确,并且我已经在架构更改之间删除了我的数据库但是无法解决这个问题。我正在运行的代码如下所示,并将自行处理。

    /* Schema */
var mongoose = require('mongoose')
  , Schema = mongoose.Schema
var ObjectId = Schema.ObjectId;

var AreaSchema = new Schema({
  name: String,
  loc: {
    type : { type : String, default : 'Polygon' },
    coordinates: []
  }
})
AreaSchema.index({coordinates: '2dsphere'});

mongoose.model('Area', AreaSchema)
var Area = mongoose.model('Area')
/* Mongo connect */

var conn = mongoose.connect('mongodb://localhost/geoPolygonExample')
// Error handler
mongoose.connection.on('error', function (err) {
  console.log(err);
});

/* Test case */
var my_area = new Area({
  "name": "Test",
  "loc": {
    "coordinates": [[
      [ -85.56045071399187, 38.215601 ],
      [ -85.56080428954273, 38.21842155313534 ],
      [ -85.5618514284852, 38.221133713995485 ],
      [ -85.56045071399187, 38.215601 ]
    ]],
    "type" : "Polygon"
  }
});
my_area.save( function (err) {
  Area
  .find({})
  .where('loc.coordinates')
  .near({
    center: [ -85.56045071399187, 38.215601 ],
    maxDistance: 100/6371,
    spherical: true
  })
  .exec(function(err, areas){
    console.log("err: ", err);
    console.log("areas: ", areas);
  //* result: err:  { [MongoError: n/a]
  //* name: 'MongoError',
  //* message: 'n/a',
  //* '$err': 'Unable to execute query: error processing query: ns=geoPolygonExample.areas limit=1000 skip=0\nTree: GEONEAR  field=loc.coordinates maxdist=0.0156961 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
  //* code: 17007 }
  //* areas:  undefined
  });

})

1 个答案:

答案 0 :(得分:1)

应在2dshpere属性上创建loc索引,而不是coordinates属性。尝试将索引语句更改为:

AreaSchema.index({loc: '2dsphere'});

此外,索引是在后台创建的,有时需要一段时间才能生成,具体取决于集合中现有数据的数量。由于您的insertfind命令在模型注册后立即运行,因此您第一次运行此代码时可能会收到错误,因为索引很可能尚不存在。