How does one represent MongoDB GeoJSON fields in a Mongoose Schema?

Zugwalt picture Zugwalt · Mar 21, 2013 · Viewed 26.5k times · Source

MongoDB 2.4 allows the use of GeoJSON objects and a slew of neat functions and indexes that I'd like to use.

It expects GeoJSON objects to be stored in the format like:

loc: {
  type: 'Polygon',
  coordinates: [[[-180.0, 10.0], [20.0, 90.0], [180.0, -5.0], [-30.0, -90.0]]]
}

So in Mongoose one would think the schema would be defined like:

loc: { type: 'string', coordinates: [[['number']]] }

But this present two problems:

  1. having a field called "type" screws up Mongoose's schema parsing because it allows defining fields in the form field: { type: , index: } etc.

  2. Mongoose does not like nested arrays.

One way to overcome this is to simply use mongoose.Schema.Types.Mixed, however I feel that there has got to be a better way!

Answer

Jed Watson picture Jed Watson · Mar 30, 2013

For reference, GeoJSON is officially supported in Mongoose 3.6

See the release notes here.

Example (from the docs):

new Schema({ loc: { type: [Number], index: '2dsphere'}})

... then ...

var geojsonPoly = { type: 'Polygon', coordinates: [[[-5,-5], ['-5',5], [5,5], [5,-5],[-5,'-5']]] }

Model.find({ loc: { $within: { $geometry: geojsonPoly }}})
// or
Model.where('loc').within.geometry(geojsonPoly)