I'm using Mongoose in my NodeJS project, and I have a GeoJSON object in a subdocument array:
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;
I added a middleware in the ChildSchema
that gets location information using geocoder
that works with mapquest.
Middleware (in 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();
}
When I try creating a new Parent document (using POST with application/json Content-Type) I'm getting the following error:
MongoError: Can't extract geo keys: {the_parent_document} geo element must be an array or object: type: \"Point\"
I tried applying the answers I found in the following questions but it didn't help:
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 ]
What am I missing? Thank you for your answers in advance!