NemoStein NemoStein - 5 months ago 33
Node.js Question

Map in Mongoose

I'm trying to create a schema in Mongoose that have a map (object, associative array, key-value pairs), but no success so far.

The documents of my schema must be something like this:

{
"_id": ObjectId("..."),
"groups"
{
"groupA":
{
"value1": "...",
"value2": "..."
},
"groupB":
{
"value3": "...",
},
"groupC":
{
"value4": "...",
"value5": "...",
},
...
}
}


groups is as object with a variable number of keys. I don't know those keys ahead of time as it'll be create by the user.

Every entry in groups is another object. As before, I don't know the key identifiers, but I know that the values are String (or Boolean, or Number, doesn't matter).

Of course, those keys are Strings.

Is it even possible (is there anyway to build such schema/model) in Mongoose?

Answer

Best practice is to keep any dynamic data out of your field names. The typical approach for a use case like this is to make groups an array and move the name of the group into a name field of the contained objects. Then you can use the Mixed type to contain the user-defined set of values:

{
    "_id": ObjectId("..."),
    "groups":
    [
        {
            name: "groupA",
            values: {
                "value1": "...",
                "value2": "..."
            }
        },
        {
            name: "groupB",
            values: {
                "value3": "..."
            }
        },
        {
            name: "groupC",
            values: {
                "value4": "...",
                "value5": "..."
            }
        },
        ...
    ]
}

You'd define the schema as:

var schema = new Schema({
    groups: [{
        name: String,
        values: Schema.Types.Mixed
    }]
});
Comments