I'm currently creating a fitting mongoose schema for our new JSON format. It is not very complex but I ran into the issue that certain values are not saved as array but rather as "normalized array" like this:
answers: [{value: 5, string: "abc"}, {value: 4, string: "def"}]
will be:
answers: {
1: {id: 1, value: 5, string: "abc"},
2: {id: 2, value: 4, string: "def"}
}
The Objects themselves can have nested "normalized arrays" as well.
For now I tried using mongoose type "Map" in the top-level-Schema like this:
answers: {
type: Map,
of: answer
}
Where "answer" is a separate mongoose.Schema itself. But all I get is:
TypeError: Undefined type `Map` at `answers`
Did you try nesting Schemas? You can only nest using refs or arrays.
Why can't I just nest maps as expected? Is it even possible to project this "normalize array" structure in a mongoose schema, and if so, how?
Thank for reading!
I was in the same situation and it seems to work for me:
const ChildSchema = new Schema({
firstName: String,
});
const ParentSchema = new Schema({
name: String,
mapProperty: { type: Map, of: ChildSchema },
});
I do also get the validation triggered from mongoose on the ChildSchema so it seems to accept it just fine.
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With