Search code examples
node.jsmongodbmongoosemongoose-schema

How do I write a Mongoose Schema for an object containing an array of arrays?


I'm trying to build a Mongoose schema for a relatively simple type. An example object coming out of mongo looks like this:

{
    "_id" : ObjectId("5df2664382f84ea90466c28e"),
    "geometry" : {
            "coordinates" : [
                    [
                            -2.600484,
                            51.446378
                    ],
                    [
                            -2.600107,
                            51.446927
                    ],
                    [
                            -2.5976,
                            51.447694
                    ],
                    [
                            -2.597077,
                            51.446343
                    ],
                    [
                            -2.598391,
                            51.446112
                    ],
                    [
                            -2.600484,
                            51.446378
                    ]
            ],
            "type" : "Polygon"
    },
    "name" : "Wapping Wharf"
}

This represents a fairly basic structure and contains an array of arrays which is where I suspect I'm going wrong in the mongo schema. This is what I have currently:

new mongoose.Schema({
    geometry: {
        coordinates: [
            [Number, Number]
        ],
        type: String
    },
    name: String
})

If I try and output the entire object returned from Mongoose within my node application I can see that a geometry property exists along with the _id and name properties. However, if I try and access geometry I get undefined. After a quick search I learned that this means the Mongoose schema is incorrect.

If I define geometry as being Schema.Types.Mixed I seem to get the object but this means I cannot define the expected schema. I've also tried defining the inner array as being Mixed but this doesn't seem to fix the issue.

Any help on this would be appreciated.


Solution

  • why didn't you try this

    new mongoose.Schema({
        geometry: {
            coordinates: [
                [{Number, Number}]
            ]
        },
        name: String
    })