【问题标题】:How to fix MongoError: no geo indices for geoNear如何修复 MongoError:geoNear 没有地理索引
【发布时间】:2019-05-30 04:13:58
【问题描述】:

我有一个几何类型的集合。现在我想,对于给定的点,获取最近的文件。我正在尝试将 $geoNear 运算符与 MongoDb 一起使用。但在我的回调中,我发现了一个错误“MongoError:geoNear 没有地理索引”。我想我必须为我的收藏定义一个索引。

所以我尝试启动这个命令: $ db..createIndex({locationCoordinate:"2dsphere"});

但这并没有改变什么。

这是我的架构定义:

const MySchema = new mongoose.Schema({
  logo: { type: String, required: true },
  locationCoordinate: {
    type: {
      type: String,
      enum: ['Point'],
      default: 'Point'
    },
    coordinates: {
      type: [Number],
      required: true,
      unique: true
    }
  },
  name: { type: String, required: true }
}, {
  writeConcern: 'majority',
});

这是我的聚合函数:

myModel.aggregate([
 {
   $geoNear: {
      near: { type: "Point", coordinates: [ 17 , 65 ] },
      distanceField: "distance",
      spherical: true
   }
 }
  ], (err, results) => {
    console.log("Err", err)
  })

我做错了什么?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    你可以这样等待索引:

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

    然后执行异步操作。

    【讨论】:

    • 谢谢。我添加了 waitForIndex 函数并在 waitForIndex 完成时执行 myModel.agregate 但我仍然有同样的错误。
    • 你应该在聚合之前使用它。即myModel.save().then(waitForIndex).then(aggregate).catch(err=> ...)@popidep
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2021-11-02
    • 2014-12-01
    • 2020-04-27
    • 2014-02-04
    • 1970-01-01
    • 2023-01-08
    相关资源
    最近更新 更多