I am using Node.js and Mongoose to access my MongoDB. I am using a model that stores some geo coordinates. I have them indexed and everything seems to work as expected. What I am trying to do is to retrieve the most near things from my request. On the MongoDB console I do something like this:
distances = db.runCommand({ geoNear : "deals", near : [11.252, 14.141], spherical : true, maxDistance : 300 }).results
However, I am not sure how to do this with Mongoose. Here is more information about the command I am trying to use: http://www.mongodb.org/display/DOCS/Geospatial+Indexing
Thanks, Jose
First of all there is not yet a convenience wrapper to use geoNear with Mongoose directly (given that you want to read the calculated distance).
But since Mongoose collections proxies all collection methods from the native MongoDB native driver you can just use their geoNear method, though you have to give up a little bit of convenience you might expect from Mongoose and in my findings the error handling was a little bit different.
Anyway, this is how you could use said API:
YourModel.collection.geoNear(lon, lat, {spherical: true, maxDistance: d}, function(err, docs) {
if (docs.results.length == 1) {
var distance = docs.results[0].dis;
var match = docs.results[0].obj;
}
});
Please refer to the docs for correct error handling and how to calculate the distances.
YourModel.db.db.executeDbCommand({geoNear : "locations", near : [11.252,14.141], spherical: true }, function(err,res) { console.log(res.documents[0].results)});
node 0.6.6, [email protected], mongodb version v2.0.2
its a bit hacky and could change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With