Using geoJSON in mongoose schema and use it in a query Using geoJSON in mongoose schema and use it in a query mongoose mongoose

Using geoJSON in mongoose schema and use it in a query


I recommand you to see the mongoDB part for geolocation datas : http://docs.mongodb.org/manual/core/2d/

To store longitude, latitude, MongoDB take you the correct data structure to save items :

To store location data as legacy coordinate pairs, use an array or an embedded document. When possible, use the array format:

loc : [ < longitude > , < latitude > ]

Consider the embedded document form:

loc : { lng : , lat : }

Arrays are preferred as certain languages do not guarantee associative map ordering.

For all points, if you use longitude and latitude, store coordinates in longitude, latitude order.

On your shema, change

start_coord: {  lon: Number,  lat: Number},

By :

start_coord: {  lng: Number,  lat: Number},

Then you should add a 2dindex for your field start_coords to use all mongoDB geospatial queries :

db.collection.ensureIndex( { start_coord : "2d" } , { min : <l ower bound > , max : < upper bound > } )

EDIT It's important to set min and max if your longitude and latitude is not a real lng/lat (for example if you could use 2dindexes in a orthonormal map)

Now you can use all geospatial query operators : http://docs.mongodb.org/manual/reference/operator/query-geospatial/


You can also do it this way:

start_coord: {    type: [Number],   // [<longitude>, <latitude>]    index: '2d'   // create the geospatial index}

Check this tutorial: How to use geospatial indexing in mongoDb