在 mongoose 中使用 $near 查询明智地获取数据位置时出错

Getting Error while fetching data location wise with $near query in mongoose

query = {
  "location" : {
       "$near" : {
                    "$geometry": {
                        "type": "Point" ,
                        "coordinates": [18.55,73.78]
                    }
                }
            }
       }
  }






planner returned error: unable to find index for $geoNear query
    at Connection.<anonymous> (D:\Projects\api\node_modules\mongodb-core\lib\connection\pool.js:443:61)
    at Connection.emit (events.js:198:13)
    at Connection.EventEmitter.emit (domain.js:466:23)
    at processMessage (D:\Projects\api\node_modules\mongodb-core\lib\connection\connection.js:364:10)
    at Socket.<anonymous> (D:\Projects\api\node_modules\mongodb-core\lib\connection\connection.js:533:15)
    at Socket.emit (events.js:198:13)
    at Socket.EventEmitter.emit (domain.js:466:23)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  ok: 0,

为此,我在下面指定的位置字段上创建了 2dsphere link

https://docs.mongodb.com/manual/core/2dsphere/

db.collectionName.createIndex( { location : "2dsphere" } )

如果我做错了什么,请帮助我理解。

尝试将 $near 更改为 $nearSphere 并在 $geometry 旁边添加 $minDistance: 0$maxDistance: yourmaxdistance 如果它仍然不起作用...所以它会看起来像

query = {
  location: {
     $nearSphere: {
        $geometry: {
            type: "Point" ,
            coordinates: [18.55,73.78],
        },
        $minDistance: 0,
        $maxDistance: //your max will go here
     }
  }
}

如果上述方法不起作用,请尝试再次创建索引并留意输出...

这是一个索引创建失败的例子...

{
        "ok" : 0,
        "errmsg" : "Unknown index plugin '2dSphere'",
        "code" : 67,
        "codeName" : "CannotCreateIndex",
        "operationTime" : Timestamp(1590940517, 1),
        "$clusterTime" : {
                "clusterTime" : Timestamp(1590940517, 1),
                "signature" : {
                        "hash" : BinData(0,""),
                        "keyId" : NumberLong("")
                }
        }
}