Unable to get $near working

Hi,

I’m trying to query People by proximity, but am not getting it working:

I create people the following way:

People.insert({
  location: {
    type: 'Point',
    coordinates: [ lng, lat ]
});

I create a geo index:

People._ensureIndex({'location.coordinates': '2dsphere'});

I use the following query:

People.find({
  location: {
    $near: { $geometry: {
      type: 'Point',
      coordinates: [ lng, lat ]
    } },
  $maxDistance: 1000
     }
   });

I get: I get: Error: Exception while polling query {"collectionName":"people","selector":{"location":{"$near":{"$geometry":{"type":"Point","coordinates":["-73.5611497","45.5005087"]}},"$maxDistance":1000}},"options":{"transform":null}}: Can't canonicalize query: BadValue geo near accepts just one argument when querying for a GeoJSON point. Extra field found: $maxDistance: 1000

Any idea?

1 Like

$maxDistance should be inside the $near object, like this:

People.find({
  location: {
    $near: {
        $geometry: {
          type: 'Point',
          coordinates: [ lng, lat ]
        },
        $maxDistance: 1000
    }
  }
});
1 Like

Thanks Guillaume; that was one of the things I’d tried. In that case I got a different error: Exception from sub people id NZsDQvx2Zwq6cZdur Error: Exception while polling query {"collectionName":"people","selector":{"location":{"$near":{"$geometry":{"type":"Point","coordinates":["-73.5611497","45.5005087"]},"$maxDistance":1000}}},"options":{"transform":null}}: $near requires a point, given { type: "Point", coordinates: [ "-73.5611497", "45.5005087" ] }

Oops, I realized I was passing strings to the Point object. I added Number():

People.find({
  location: {
    $near: {
      $geometry: {
        type: 'Point',
        coordinates: [ Number(lng), Number(lat) ]
      },
      $maxDistance: 1000
    }
  }
});

It’s still not working: Unable to execute query: error processing query: ns=meteor.people limit=0 skip=0 [...] Tree: GEONEAR field=location maxdist=1000 isNearSphere=0 Sort: {} Proj: {} planner returned error: unable to find index for $geoNear query

I have the following index:

{
  "v" : 1,
  "key" : {
  	"location.coordinates" : "2dsphere"
  },
  "name" : "location.coordinates_2dsphere",
  "ns" : "meteor.people",
  "safe" : true,
  "2dsphereIndexVersion" : 2
}

You made wrong index. Hole field location must be ‘2dsphere’ index.

People._ensureIndex({'location': '2dsphere'});
2 Likes

Oh, good catch. Bingo.
This was from an old version of the code where I was trying to use the deprecated $near form.
Thanks!!!