One morning someone asked for help on #mongodb…
dreambox: hey guys, I'm trying to do a within() geometry thingie... dreambox: I'm not a DB guy , total noob so please be gentle dreambox: I get a bad request.
…with this (reformatted, partial) sample code
Geometry? Within? I’ve never seen this before but it looks like fun!
I still wasn’t sure what the data to be queried should look like, until I found this primer on geospatial data and mongoDB.
Now it’s starting to make sense.
I added some locations to documents in the app I’m working on (even though it doesn’t really make sense for a rabbit to have a location… they pretty much stay in the cage where you put them.)
…and tried the OP’s query. That caused a syntax error…
TypeError: Object #<Cursor> has no method 'where'
…because I’m not using the Mongoose ORM.
I changed my query to plain mongoDB syntax and asked it to find all the rabbits within the one-unit box starting at [0,0]:
It correctly returned the rabbit (above) at [ 0.5, 0.75 ], but none of the other ones. Success!
One of the issues with the OP’s query is the coordinates for the polygon. It needs to be a closed shape with the first point being the same as the last. (I wonder what happens if you give it something like a figure eight??)
Another possible issue for the OP was the use of a legacy embedded document format for the location data instead of the newer GeoJSON format shown above. Since this is new development, there’s no reason to use the legacy format.
Later, I created an example app that lets you add and delete items, which have a location, and then query for them. You can find it on GitHub at geojson-example, and here are some screen shots: