Search code examples
node.jsmongoosegeolocation

Geo Location : unable to find index for $geoNear query in nodejs


I want to find near by geo locations using LatLong, here is my code :

var locationSchema = new Schema({

name : {
    required : "Name is required",
    type     : String
},

address : {
    required : "address is required",
    type     : [Number],
    index    : '2d'
},

createdAt : {
    type : Date,
    default : new Date()
}
});

module.exports = mongoose.model('Location', locationSchema);

Now I have data in collection and I want to fetch all documents withing range of 3 KMs of provided Latlong.

Here is my controller code for getting data :

myLocation : function (req, res) {
var coords = [],
        maxDistance = 3;

    coords[0] = parseFloat(req.query.longitude);
    coords[1] = parseFloat(req.query.latitude);
    maxDistance /= 6371; // divide by this number as earth's approximate radius is 6371 KMs.
Location.find({
            location : {
                $near           : coords,
                $maxDistance    : maxDistance
            }
        }, function (err, locations) {
            if (err) {
                res.send(err);
            } else {
                console.log("Location list");
                res.send(locations);
            }
        });

{ MongoError: error processing query: ns=geolocation.locationTree: GEONEAR  field=location maxdist=0.000470884 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error: unable to find index for $geoNear query
    at Function.MongoError.create (/var/www/NodeJS/GeoLocation/node_modules/mongodb-core/lib/error.js:31:11)
    at queryCallback (/var/www/NodeJS/GeoLocation/node_modules/mongodb-core/lib/cursor.js:212:36)
    at /var/www/NodeJS/GeoLocation/node_modules/mongodb-core/lib/connection/pool.js:469:18
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  name: 'MongoError',
  message: 'error processing query: ns=geolocation.locationTree: GEONEAR  field=location maxdist=0.000470884 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
  ok: 0,
  errmsg: 'error processing query: ns=geolocation.locationTree: GEONEAR  field=location maxdist=0.000470884 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
  code: 2,
  codeName: 'BadValue' }

Solution

  • Location.find({
                address: {
                    $near: {
                        $geometry : {
                            type: 'Point',
                            coordinates: coords
                        },
                        $maxDistance    : maxDistance * 1000
                    }
                }
            }, function (err, locations) {
               console.log(locations);
            });