Find with custom condition in mongoose

I'm developing a node.js web-app where I'm using mongoose and MongoDB for storage. It's a gelocation app. so sometimes I have to find the 10 nearest places stored in database. I have this method to calculate this distance:

var haversine = function(p1, p2) {
var R = 6371; // km
var dLat = toRad(p2.lat-p1.lat);
var dLon = toRad(p2.lon-p1.lon);
var lat1 = toRad(p1.lat);
var lat2 = toRad(p2.lat);

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;

return d;
 }

where p1 and p2 are points {lat: Integer, lon: Integer}.

So, How should I do to find the nearest places?

Problem courtesy of: Javier Manzano

Solution

Apologies if I am not understanding the question, but if you have a lat and lon stored in MongoDB already, why not just ensure a Geo index on that key and use MongoDB itself to find the nearest points.

Assuming a Geo index on location key consisting of lat and lon, you can simply issue something similar to the following:

db.places.find( { location : { $near : [lon,lat] } } ).limit(10)

Which should find the nearest ten places in your database to the location defined at lon,lat.

You can find more information at the documentation for geospatial indexing.

Solution courtesy of: Andre de Frere