Search code examples
node.jsmongodbmongoosegeospatial2dsphere

MongoDB geospatial query does not return anything


I have a collection with a 2dsphere index and want to use the $geoWithin and $centerSphere functions to query it.

Excerpt of the model:

{
// ...
coordinates: {
    coordinates: {
        type: Array,
        index: '2dsphere'
    }
}
// ...
}

I successfully inserted a bunch of documents into the database and now try to query it via:

Model.find({
    coordinates: {
        coordinates: {
            $geoWithin: {
                $centerSphere : [ [ lng, lat], r ]
            }
        }
    }
})

The problem I am facing is, that the call does not return anything, neither an error, nor data. I tried it in the mongo shell as well as in my node.js application with longitudes and latitudes of objects I can confirm were inserted into the database. I also tried to use $near with a $maxDistance with the same result. I furthermore switched latitude and longitude just to check...and I do convert r to radians by dividing by the earth's radius.

I am out of ideas on what goes wrong at this point and thankful for any suggestions!


Solution

  • I think you should change your model but, use "dot notation" instead:

    Model.find({
        "coordinates.coordinates": {
            "$geoWithin": {
                "$centerSphere" : [ [ lng, lat], r ]
            }            
        }
    },function(err,callback) {
    
    });