Search code examples
node.jsmongodbmongoosegeolocationgeometry

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,

For this I have created 2dsphere on location field as specified in the below link

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

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

Help me to understand If I am doing anything wrong.


Solution

  • try changing $near to $nearSphere and also add $minDistance: 0 and $maxDistance: yourmaxdistance next to $geometry if it still doesnt work...so it will look like

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

    If the above does not work try creating the index again and keep a look out for the output...

    Here is an example of an index creation that did not work...

    {
            "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("")
                    }
            }
    }