【问题标题】:Failure when searching for all polygons near a point using mongoose/mongodb使用 mongoose/mongodb 搜索点附近的所有多边形时失败
【发布时间】:2015-06-02 08:07:54
【问题描述】:

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

我有以下但我得到一个错误:

'无法执行查询:错误处理查询:ns=geoPolygonExample.areas limit=1000 skip=0\nTree: GEONEAR field=loc.coordinates maxdist=0.0156961 isNearSphere=1\nSort: {}\nProj: {}\ n 规划器返回错误:无法找到 $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
  });

})

【问题讨论】:

  • 我还检查了 GeoJSON linter,所以我相信我的 GeoJSON 是准确的。

标签: node.js mongodb mongoose geospatial geojson


【解决方案1】:

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

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

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

【讨论】:

  • 哇,这就是问题所在。非常感谢。
猜你喜欢
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 2013-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多