I have a Node.js test in which multiple Objects simulates to move away from some point in a map and I'm continuously testing if they´re within a radius from that point.
Each object corresponds to a Model with a nested legacy 2d Index 'location.loc'
.
I have used these queries
var center={_lat:20,lng:-100};
var area = {
center: [center._lng,center._lat],
radius: 100,//This are supossed to be meters
unique: true,
spherical: true }
MyModel.where('location.loc')
.within()
.circle(area)
.exec(function (err, records) {
if (err) {
throw err;
}
//Log Length of records
});
And
MyModel.find({
"location.loc": {
$near: [center._lng,center._lat],
$maxDistance: 1 //This is suposed to be a mile
}
}).exec(function(err, documents) {
if (err) {
throw err;
}
//Log documents length
});
But both scripts returns me the entire collection of documents, even when they are miles away from the point. At the same time I'm doing the same queries in my Mongo client with $near,$geoWithin and those queries gives me the right answer.
What is wrong with my Mongoose scripts?
Should only test with within().circle() for this scenario?
Turn out that the radius in the first code are wrongly defined. In this Mongo documentation says
With spherical: true, if you specify a GeoJSON point, MongoDB uses meters as the unit of measurement
But this is for a GeoJSON point and for geoNear
.
For the legacy coordinate format [long,lat], we must divide the radius value in miles by 3963.2 to cast it as radians. See this Example.