如何在Mongoose Schema中表示MongoDB GeoJSON字段?

Zug*_*alt 29 schema geospatial mongoose mongodb geojson

MongoDB 2.4允许使用GeoJSON对象和一系列我想要使​​用的简洁函数和索引.

它希望GeoJSON对象以如下格式存储:

loc: {
  type: 'Polygon',
  coordinates: [[[-180.0, 10.0], [20.0, 90.0], [180.0, -5.0], [-30.0, -90.0]]]
}
Run Code Online (Sandbox Code Playgroud)

所以在Mongoose中,人们会认为模式定义如下:

loc: { type: 'string', coordinates: [[['number']]] }
Run Code Online (Sandbox Code Playgroud)

但目前存在两个问题:

  1. 有一个名为"type"的字段搞砸了Mongoose的模式解析,因为它允许在表单字段中定义字段:{type:,index:}等.

  2. Mongoose不喜欢嵌套数组.

解决这个问题的一种方法是简单地使用mongoose.Schema.Types.Mixed,但我觉得必须有更好的方法!

Jed*_*son 47

作为参考,GeoJSON在Mongoose 3.6中得到官方支持

请参阅此处的发行说明.

示例(来自文档):

new Schema({ loc: { type: [Number], index: '2dsphere'}})
Run Code Online (Sandbox Code Playgroud)

... 然后 ...

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)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但是如何定义类型?就像我需要定义多边形或线或多点? (3认同)
  • 你只需将`loc`路径的值设置为这样的数组:`item.loc = [lng,lat]; item.save()` (2认同)

aar*_*ann 15

您必须使用Mixed来表示数组的数组.将来会有一张开放的机票来支持这一点.

@nevi_me是正确的,您必须type按照他的描述声明属性.

这是一个要点:https://gist.github.com/aheckmann/5241574

有关更多想法,请参阅此处的猫鼬测试:https://github.com/LearnBoost/mongoose/blob/master/test/model.querying.test.js#L1931

  • 谢谢!在Mongoose文档中看到对此的解释会很高兴. (3认同)

Mar*_*erg 5

猫鼬,以GeoJSON-架构包是为了让您轻松拥有以GeoJSON在猫鼬架构.


arg*_*g20 5

Mongoose 现在正式支持这一点

简而言之,您所做的是,对于该模式,您使用typeKey设置告诉猫鼬使用不同的键来获取类型信息。下面是一个例子:

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
Run Code Online (Sandbox Code Playgroud)

因此,现在不是type使用属性声明类型信息,而是使用$type. 这适用于模式级别,因此在需要它的模式中使用它。