首页 > 解决方案 > 找不到 $geoNear 查询的索引,代码:2,代号:'badValue'

问题描述

这是我的架构

    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.jsmongodbmongoosegeo2dsphere

解决方案


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

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

因此,只需再次检查您对位置的定义。type值在这里始终固定为“点”,尝试将其建模为静态值。并且您指定的索引应该在location not inside type

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

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

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

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

推荐阅读