Search code examples
javascriptnode.jsmongodbmongoosegeojson

How to find if a coordinate is within a polygon in mongoose for node js


I have tried many different attempts but have failed. Currently, my query doesn't fail but it doesn't provide me any results. I am using Mongoose v 3.8.9 which uses Mongodb v 1.4. I think my coordinates are indexed properly, since it works for quering using .geoNear(). However, geoNear() only allows for a single coordinate and hence I can't specifty g

Here is a sample of it that runs but doesn't return any result. I have even changed one of the documents to contain the point exactly to one of the four points specified in geoJSONpolygon.

 var geoJSONpolygon = { type: 'Polygon',coordinates:[[43.6582231,-79.3988945],[43.6583683,-79.3980648],[43.6583143,-79.3979845],[43.6584212,-79.3975422]] }

  newLocation.find({}).where('pos').within().geometry(geoJSONpolygon).lean().exec(function(err,doc){
    console.log(doc);
    res.send(doc);
});

Solution

  • That's what I use, might help you.

       Position.find(
            { geo :
                         { $geoWithin : { $box :
                                          [ [ box[0] , box[1] ] ,
                                            [ box[2] , box[3] ] ] } }
    
        }, function(err, response) {
            if (err) return err;
    
            console.log(response)
    
        });    
    

    You can also set to debug and check the result:

    mongoose.set('debug', true)