我在NodeJS项目中使用Mongoose,并且在子文档数组中有一个GeoJSON对象:
ParentSchema.js
import mongoose from 'mongoose';
import ChildeSchema from '[path]/ChildSchema.js';
const ParentSchema = mongoose.Schema({
...
children: [ChildSchema],
...
});
ChildSchema.js
import mongoose from 'mongoose';
import geocoder from '[path]/geocoder.js'; // where I initialize the geocoder
const ChildSchema = mongoose.Schema({
...
location: {
// GeoJSON
type: {
type: String,
enum: ['Point'],
default: 'Point'
},
// first enter longitude, then latitude
coordinates: {
type: [Number]
//index: '2dsphere' <-- committed out, also tried with the index
}
},
...
});
// middleware goes here
export default ChildSchema;
我在ChildSchema
中添加了一个中间件,该中间件使用与{em> mapquest 一起使用的geocoder
来获取位置信息。
中间件(在ChildSchema.js中):
ChildScheme.pre('save', async function (next) {
const geoDetails = await geocoder.geocode(this.fullAddress); // works fine, I'm getting the location
// values are legal
const latitude = geoDetails[0].latitude;
const longitude = geoDetails[0].longitude;
this.location = {
type: 'Point',
coordinates: [longitude, latitude]
};
next();
}
当我尝试创建新的父级文档(将POST与application / json Content-Type结合使用)时,出现以下错误:
MongoError:无法提取地理键: {the_parent_document} 地理元素必须是数组或对象:类型:\“ Point \”
我尝试应用在以下问题中找到的答案,但没有帮助:
mongoose geojson in schema, “Can't extract geo keys” error
MongoError: Can't extract geo keys
Mongoose Schema for geoJson coordinates
How does one represent MongoDB GeoJSON fields in a Mongoose Schema?
Can't extract geo keys, unknown GeoJSON type: { coordinates: [ 13.42493130000003, 52.50074619999999 ]
我想念什么?谢谢您提前回答!
答案 0 :(得分:1)
将密钥的名称更改为{{1}}以外的其他名称,并且有效...