'Mongoose query with formula including 2 columns, Latitude and Longitude, in Node js
I have a collection users which contains two fields: latitude and longitude.
I am making a node js request which contain current latitude and current longitude.
I need to make a query that will calculate Haversine Formula and return results within 5 km.
Is there anyone who can help me write this query using mongoose in node js
Solution 1:[1]
I haven't tried computing it manually, but mongoose has some inbuilt functions to get the points that are close to other points so maybe this helps someone.
You can use the geojson data format to store your coordinates in MongoDb, then query using $near. It accepts a distance in meters for the $maxDistance parameter, so you can do something like:
Model.find({
location: {
$near: {
$maxDistance: distanceMeters,
$geometry: {
type: "Point",
coordinates: coordinates // your reference coordinates as [longitude, latitude],
},
},
},
});
Bonus: You can index the location field for faster lookups :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bianca |
