【发布时间】:2020-07-31 04:08:24
【问题描述】:
我在我的 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 中添加了一个中间件,它使用与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();
}
当我尝试创建一个新的父文档(使用带有 application/json Content-Type 的 POST)时,我收到以下错误:
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?
@987654325 @
我错过了什么?提前感谢您的回答!
【问题讨论】:
标签: javascript node.js mongodb mongoose geojson