Reputation: 1568
I have a user schema (mongoose) which has the field 'location'- it consists of an array of [longitude, latitude]
now, i wish to query the db, using the geospatial services, in order to find the distance from user1 to user2
How do i do that?
Upvotes: 1
Views: 4773
Reputation: 1186
This should get you started
You need to define a property in your schema:
'location' : {
type: { type: String },
coordinates: []
},
And index the property as 2dsphere
yourSchema.index({'location' : "2dsphere"})
Than you can do the following:
//Model.geoNear(GeoJSON, options, [callback]) need a GeoJSON point to search in radius
var point = { type : "Point", coordinates : [data.coordinates.long, data.coordinates.lat] };
YourModel.geoNear(point, { maxDistance : data.distance /coordinatesUtils.earthRadius, spherical : true }, function(err, results, stats) {
res.status(200);
res.json(results);
});
But there are a few things to note:
For spherical query operators to function properly, you must convert distances to radians, and convert from radians to the distances units used by your application.
To convert: distance to radians: divide the distance by the radius of the sphere (e.g. the Earth) in the same units as the distance measurement.
radians to distance: multiply the radian measure by the radius of the sphere (e.g. the Earth) in the units system that you want to convert the distance to.
The radius of the Earth is approximately 3,959 miles or 6,371 kilometers.
Taken from here
There was a bug in mongoose that strip the coordinate from the GeoJSON and send them like legacy pair to mongo which causes the near operation to work in radians instead of meters.
It might be fixed now but I am not sure.
You can also read in the document for geoNear in mongoose api site
You can read about GeoJson here
Upvotes: 3