nodejs-猫鼬5.3.8-GeoJSON查询不起作用

时间:2018-11-02 07:07:29

标签: node.js mongodb mongoose 2dsphere mongodb-geospatial

我试图使用Mongoose 5.3.8基于坐标点存储和查询位置,以便返回另一个点半径内的点。 我已经阅读了文档,并在部分中实现了pointSchema + citySchema示例: Using GeoJSON data如下所示

const pointSchema = new mongoose.Schema({
  type: {
    type: String,
    enum: ['Point'],
    required: true
  },
  coordinates: {
    type: [Number],
    required: true
  }
});

const citySchema = new mongoose.Schema({
  name: String,
  location: {
    type: pointSchema,
    required: true
  }
});

具有一个express端点,我使用以下代码和一个存储为以下内容的文档查询一个mLab实例:

DOCUMENT ---------------------------

{
    "_id": "5bdbeb78949541086880dd35",
    "name": "Location1",
    "location": {
        "coordinates": [
            48.5,
            -123.8
        ],
        "_id": "5bdbeb78949541086880dd36",
        "type": "Point"
    }
}

QUERY --------------------------------

Location.findOne({
   location: {
     $near: {
       $geometry: {
          type: "Point" ,
          coordinates: coordinates // [long, latt]
       },
       $maxDistance: 10000,
       $minDistance: 1
     }
    }
  }).then(res => console.log(res))
    .catch(err => console.log(err))

以上查询捕获到错误:

 planner returned error: unable to find index for $geoNear query

我试图通过调用.index()在LocationSchema上添加索引

LocationSchema.index({ "location": "2dsphere" });

我还尝试通过以下方式向架构添加索引:

LocationSchema.index({ category: 1, location: "2dsphere" });

在架构上未创建索引,并且错误仍然存​​在。


我尝试了其他几种模式/查询组合,包括:

  1. Mongoose geospatial search: distance not working-2016年2月7日
  2. Mongoose Geospatial Queries with $near-2018年4月10日
  3. unable to find index for $geoNear query #6549-2018年5月31日
  4. Net Ninja's GeoJSON tutorial-2017年3月27日

尽管使用附近的坐标进行查询,但我都没有返回另一个点半径内的点。我不知道哪里出了问题。

  • 是否存在一个可以在猫鼬5.3.8中返回另一个点半径内的点的地理空间查询的可行示例?

编辑:已澄清的问题

编辑:

开始工作。 在连接到mLab实例的猫鼬选项中,我的选择如下:

    const mongoOptions = {
  useCreateIndex: true,
  useNewUrlParser: true,
  autoIndex: false,
  reconnectTries: Number.MAX_VALUE,
  reconnectInterval: 500,
  poolSize: 10,
  bufferMaxEntries: 0
};

使用autoIndex: false参数使得即使指定LocationSchema.index({ "location": "2dsphere" });也不能创建新索引。 要解决此问题,出于某种原因,我必须添加LocationSchema.options.autoIndex = true;。希望这可以对某人有所帮助。

0 个答案:

没有答案