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)
但目前存在两个问题:
有一个名为"type"的字段搞砸了Mongoose的模式解析,因为它允许在表单字段中定义字段:{type:,index:}等.
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)
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 现在正式支持这一点。
简而言之,您所做的是,对于该模式,您使用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
. 这适用于模式级别,因此在需要它的模式中使用它。