Start a new topic

geoNear: How should I setup a collection to use geoNear method on it?

I haven't found examples on how to use geoNear on Kinvey, so I am making some test and I always end up having null as result.

[Kinvey reference]( "Kinvey reference") says that the parameters for the function are:

geoNear(x, y, options, callback)

[MongoDB ]( "MongoDB reference") says the same and shows an example.

In the example some documents are added to a collection:

{a:1, loc:[50, 30]}

{a:1, loc:[30, 50]}

and then geoNear is called with this syntax:

collection.geoNear(50, 50, {query:{a:1}, num:1}, function(err, docs) { ... });

On my Kinvey BL test I created a collection, with some documents like:

{_id:54e7448fd2c14b30080025f2, a:1, loc:[50, 30]}

{_id:54e7448fd2c14b30080025f3, a:1, loc:[30, 50]}

and I try to run the geoNear method in the same way:

modules.collectionAccess.collection("geotest").geoNear(50, 50, {query:{a:1}, num:1}, function(err, docs) { ... });

but as written earlier, I get a null result.

One thing I understood is that, in order to use geoNear, I need to add a location based index, is that right? In MongoDB documentation that's what is happening, before to create the docs, the collection index is set with:

collection.ensureIndex({loc:"2d"}, function(err, result) { ... });

Is that my problem? And if it is, how do I recreate it in Kinvey?

Okkeyyyyy, the answer was easier than I thought, I have been trying for 1h before without finding it, now I found it immediately, I just had to look somewhere else.

On the [Kinvey Location guide]( "Kinvey Location guide") is written "With Kinvey all you need to do to your object is add a field with name _geoloc with a [lon,lat] value."

And so it is. I changed those documents into:

{_id:54e7448fd2c14b30080025f2, a:1, _geoloc:[50, 30]}

{_id:54e7448fd2c14b30080025f3, a:1, _geoloc:[30, 50]}

And now it's working fine.

I hope this could be helpful for somebody else in the future ;)

I'm glad you were able to find this one on your own, please feel free to reach out if you get stuck in the future.

Login or Signup to post a comment