Search code examples
node.jsmongodbgeojson

how to save geojson with mongodb?


I am trying to save a geojson, using mongoose and nodejs, for the moment I want to save a geojson of type 'MultiPoint'

this is the scheme that I have defined to save the geojson

let capaSchema = new Schema({
nombrecapa: {
    type: String,
    required: [true, 'El nombre de la capa es necesario']
},
descripcion: {
    type: String,
    required: [false]
},
geojson: Object([
    geoSchema
])
});
const geoSchema = new Schema({
type: {
    type: String,
    default: 'FeatureCollection',
},
features: [
    Object({
        type: {
            type: String,
            default: 'Feature',
        },
        geometry: {
            type: {
                type: String,
                default: 'MultiPoint'
            },

            coordinates: {
                type: [
                    Number
                ],
                index: '2dsphere'
            }
        }
    })
],
});

this is the object that I want to save using the save method of moongose, first I make an instance of the schema, maybe my error may be inside the instance.

let capa = new Capa({
    nombrecapa: body.nombrecapa,
    descripcion: body.descripcion,
    geojson: {
        type: body.typefeature,
        features: [{
                type: body.featurestype,
                geometry: {
                    type: body.geometrytype,
                    coordinates: [
                        [-105.01621, 39.57422],
                        [-105.01231, 39.57321]
                    ]

                }
            }

        ]
    }
});

capa.save((err, capadb) => {
        if (err) {
            return res.status(400).json({
                ok: false,
                err
            })
        }
        res.json({
            ok: true,
            capa: capadb
        })
    })

but at the time of saving I returned the following errors:

"_message": "Capa validation failed",
    "message": "Capa validation failed: geojson.0.features.0.geometry.coordinates: Cast to Array failed for value \"[ [ -105.01621, 39.57422 ], [ -105.01231, 39.57321 ] ]\" at path \"geometry.coordinates\"",
    "name": "ValidationError"

Solution

  • In your schema you have coordinates as a single array but the data being passed is actually an array of nested arrays

    I think what you need here is

    coordinates: {
      type: [[Number]],
      index: '2dsphere'
    }