$ near error - planner返回错误:无法找到$ geoNear查询的索引

问题描述 投票:1回答:1

我遇到这个问题很麻烦。我正在构建一个小API来获取最近存储的元素(在mlab MongoDB中)给定特定的坐标。

我想使用Mongo自定义查询工具(如$ near)从我的数据库中获取最接近的元素。

你可以找到原始的回购here

The Data

原始数据有点.csv,我转换为geojson格式。

这是.csv的简短版本:

A little csv containing events coordinates

这是它的geojson版本:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.4049238868200975, 48.82094216189432]
      },
      "properties": {
        "event_type": "imp"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.3645320381923534, 48.816341825787724]
      },
      "properties": {
        "event_type": "imp"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.3274838513968072, 48.86982967859056]
      },
      "properties": {
        "event_type": "imp"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.23284629237154, 48.89111120713999]
      },
      "properties": {
        "event_type": "imp"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.23284629237154, 48.89111120713999]
      },
      "properties": {
        "event_type": "click"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.4204737962258305, 48.85038737901075]
      },
      "properties": {
        "event_type": "imp"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.4214870126092594, 48.86339618816508]
      },
      "properties": {
        "event_type": "imp"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.4144620076022436, 48.876530301936576]
      },
      "properties": {
        "event_type": "imp"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.2470618097659285, 48.88845096504584]
      },
      "properties": {
        "event_type": "imp"
      }
    }
  ]
}

The Model

这是使用mongoose的模式(如你所见,我确实添加了2dsphere索引):

const mongoose = require("mongoose");

const FeatureSchema = new mongoose.Schema({
  type: String,
  geometry: {
    type: { type: String, default: "Point" },
    coordinates: { type: [Number] }
  },
  properties: { event_type: String }
});

FeatureSchema.index({ geometry: "2dsphere" });
const MapEventSchema = new mongoose.Schema({
  type: String,
  features: [FeatureSchema]
});

const MapEvent = mongoose.model("mapEvent", MapEventSchema);

module.exports = MapEvent;

The Test

现在是我正在努力的测试(使用Mocha):

const assert = require("assert");
const MapEvent = require("../src/models/mapEvents");
const fs = require("fs");

describe("Read test", () => {
  // create new room collection because collection is drop between each file
  beforeEach(done => {
    rawJSON = fs.readFileSync("./src/assets/test_assets/read_test.json");
    const parsedContent = JSON.parse(rawJSON);
    const mapEvent = new MapEvent(parsedContent);
    mapEvent
      .save()
      .then(() => {
        done();
      })
      .catch(error => {
        console.error(error);
      });
  });

  it("Find nearest event by coordonates", done => {
    const distance = 1000;
    const lat = 48.86;
    const lon = 2.35;

    function waitForIndex() {
      return new Promise((resolve, reject) => {
        MapEvent.on("index", error => (error ? reject(error) : resolve()));
      });
    }

    MapEvent.findOne({
      geometry: {
        $near: [lat, lon],
        $maxDistance: distance
      }
    })
      //.then(waitForIndex)
      .then(MapEvent.init())
      .then(nearestResult => {
        console.log("------------");
        console.log(nearestResult);
        console.log("------E-----");
        assert(nearestResult);
        done();
      })
      .catch(error => {
        console.error("************");
        console.error(error);
        console.error("******E*****");
      });
  });
}); 

The Output

正如您可能注意到的,我注释掉waitForIndex()(找到相关的Stackoverflow问题)来使用MapEvent.init()代替(在github上找到)。不幸的是,两种解决方案都给我相同的错误输出。

Connection is established
  Create test
(node:12483) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
    ✓ MapEvent saving

  Read test
************
{ MongoError: error processing query: ns=babylon_ad_db.mapevents batchSize=1 limit=1Tree: GEONEAR  field=geometry maxdist=1000 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error: unable to find index for $geoNear query
    at queryCallback (/home/geoffrey/babylon-ad/node_modules/mongodb-core/lib/cursor.js:248:25)
    at /home/geoffrey/babylon-ad/node_modules/mongodb-core/lib/connection/pool.js:532:18
    at process._tickCallback (internal/process/next_tick.js:61:11)
  ok: 0,
  errmsg:
   'error processing query: ns=babylon_ad_db.mapevents batchSize=1 limit=1Tree: GEONEAR  field=geometry maxdist=1000 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
  code: 2,
  codeName: 'BadValue',
  operationTime:
   Timestamp { _bsontype: 'Timestamp', low_: 7, high_: 1536667477 },
  '$clusterTime':
   { clusterTime:
      Timestamp { _bsontype: 'Timestamp', low_: 7, high_: 1536667477 },
     signature: { hash: [Binary], keyId: [Long] } },
  name: 'MongoError',
  [Symbol(mongoErrorContextSymbol)]: {} }
******E*****
    1) Find nearest event by coordonates


  1 passing (3s)
  1 failing

  1) Read test
       Find nearest event by coordonates:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/geoffrey/babylon-ad/test/read_test.js)

我已经做了一些谷歌搜索,这是我听到$ near和2dsphere索引的方式。但是,我仍然无法弄清楚为什么它说找不到索引。即使我用waitForIndex()或MapEvent.init()等待它。

这个社区做了一些很酷的奇迹,我希望你会帮助我。

谢谢,

node.js mongodb mongoose geolocation geojson
1个回答
3
投票

此类错误表示未创建索引。通常这是由于无效的坐标数据。也许加载你的mongo shell并确保你的索引存在:

mongo
use yourdatabasename
db.yourcollection.getIndexes()

你应该得到类似的东西:

{
    "v" : 2,
    "key" : {
      "geometry" : "2dsphere"
    },
    "name" : "geometry_2dsphere",
    "ns" : "databasename.yourcollection",
    "2dsphereIndexVersion" : 3
  }

如果不存在,尝试在shell中创建索引 - 如果无法创建一个,它将抛出错误:

db.yourcollection.createIndex( { geometry : "2dsphere" } )
© www.soinside.com 2019 - 2024. All rights reserved.