【问题标题】:Unable to find index for $geoNear query, code: 2, code-name: 'badValue'找不到 $geoNear 查询的索引,代码:2,代号:'badValue'
【发布时间】:2020-01-30 03:54:24
【问题描述】:

这是我的架构

    const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    skills: [{
        type: String
    }],
    location: {
        type: {
            type: String,
            index: '2dsphere'
        },

        coordinates: []
    }
});

我的查询看起来像这样

    User.find({
    location: {
        $nearSphere: {
            $geometry: {
                type: "Point",
                coordinates: [77.032448, 28.590654]
            },
            $maxDistance: 2000
        }
    }
   }).find((error, results) => {
    if (error) console.log(error);
    console.log(results);
   });

每当我运行代码时,我都会收到此错误

    ok: 0,
  errmsg:
   'error processing query: ns=StudyJamm.usersTree: GEONEAR  field=location maxdist=2000 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
  code: 2,
  codeName: 'BadValue',
  name: 'MongoError',
  [Symbol(mongoErrorContextSymbol)]: {}

PS:- 我已经试过User.index({location: "2dsphere"});

我在这里做错了什么? 我已经解决了有关 Stack Overflow 的所有类似问题,但没有适合我的解决方案。

【问题讨论】:

    标签: node.js mongodb mongoose geo 2dsphere


    【解决方案1】:

    位置将像下面一样存储在 mongoDB 中。

    location: {
          type: "Point",
          coordinates: [-73.856077, 40.848447]
    }
    

    因此,请再次检查您对位置的定义。 type 值在这里始终固定为“点”,尝试将其建模为静态值。您指定的索引应该在location 上,而不是在type 内。

    您可以从数据库中检查此查询是否创建了索引

    db.getCollection('data').getIndexes()
    

    如果不是,则索引创建有问题。我从https://mongoosejs.com/docs/api.html#schematype_SchemaType-index得到以下代码

    var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
    

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 2018-10-28
      • 2015-01-06
      • 1970-01-01
      • 2017-03-24
      • 2021-10-28
      相关资源
      最近更新 更多