Skip to content
Advertisement

How to get a boolean value if a location coordinate is within the given $geoWithin or $geoNear radius in mongoose?

I want to get a boolean value eg. true or false if a location coordinate is within the given radius is the $geoWithin query or $geoNear pipeline in mongoose aggregate function. If I user $geoNear in the mongoose aggregate pipeline then it only returns the filtered result. So far I have done the following,

The Model:

JavaScript

The function in my controller:

JavaScript

In the above snippet, I have a field called isViewable. Right now I am updating this field in runtime. But I want to update this field in the aggregation pipeline. Is there any way to check if the location coordinate is within the provided $geoWithin or $geoNear from the aggregation pipeline? Thanks.

Advertisement

Answer

If you’re fine with using $geoNear (you need the 2dsphere index & it must be the first stage in the pipeline as noted in docs) you could add a distance field and then another field which will output a boolean based on it, like so:

JavaScript

And optionally unset the distance field in another stage if you don’t need it.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement