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

瘦欲@ 提交于 2019-11-28 15:48:58

You must used Mixed to represent arrays of arrays. There is an open ticket to support this in the future.

@nevi_me is correct, you must declare the type property as he described.

Here's a gist: https://gist.github.com/aheckmann/5241574

See the mongoose tests here for more ideas: https://github.com/LearnBoost/mongoose/blob/master/test/model.querying.test.js#L1931

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)

The mongoose-geojson-schema package was created to make it easy to have GeoJSON in Mongoose Schemas.

I'm about to start moving all my location references in my MongoDB from '2d' to GeoJSON, so I'll encounter the same problem.

  • Regarding the type problem, you have to follow what I did below to get it working. Mongoose correctly recognises it as a string.
  • Nested arrays; I agree that mongoose.Schema.Types.Mixed will work, but I think you can try what I did below, let me know if it works. I'm not near a PC with mongo installed to try the schema out.

Here's how I'd define the schema. The nested array can be tweaked to work, so let me know if it doesn't.

var LocationObject = new Schema ({
  'type': {
    type: String,
    required: true,
    enum: ['Point', 'LineString', 'Polygon'],
    default: 'Point'
  },
  coordinates: [
    [
      { type: [ Number ]
    ]
  ]
});

If you get undesired results in the nesting of the Array, try this out instead. Basically nesting in deeper.

coordinates: [
  { type: [
    { type: [ Number ] }
  ] }
]

Mongoose now officially supports this.

In a nutshell, what you do is, for that schema, you use the typeKey setting to tell mongoose to use a different key for type information. Here is an example:

var schema = new Schema({
  // Mongoose interpets this as 'loc is an object with 2 keys, type and coordinates'
  loc: { type: String, coordinates: [Number] },
  // Mongoose interprets this as 'name is a String'
  name: { $type: String }
}, { typeKey: '$type' }); // A '$type' key means this object is a type declaration

So now instead of declaring type info with the type property, you use $type. This works at the schema level so use it in the schemas that need it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!