Mongoose模式中的嵌套映射

3

我目前正在为我们的新JSON格式创建一个适合的mongoose模式。 它并不是非常复杂,但我遇到了一个问题,某些值并不保存为数组,而是保存为“归一化数组”,就像这样:

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"}
       }

这些对象本身也可以有嵌套的“规范化数组”。

目前我尝试在顶级模式中使用mongoose类型“Map”,如下所示:

 answers: {
    type: Map,
    of: answer
}

"answer"是一个独立的mongoose.Schema。

但是我得到的只有:

    TypeError: Undefined type `Map` at `answers`
  Did you try nesting Schemas? You can only nest using refs or arrays.

为什么我不能像预期的那样嵌套映射?在mongoose模式中是否可能投影这种“规范化数组”结构,如果是,如何实现?

谢谢阅读!


你找到任何答案了吗?我针对相同的用例已经完成了。 - Jonas Pauthier
1个回答

1
我曾经处于相同的情况,这对我似乎有用:
const ChildSchema = new Schema({
  firstName: String,
});

const ParentSchema = new Schema({
  name: String,
  mapProperty: { type: Map, of: ChildSchema },
});

我也从mongoose的ChildSchema中触发了验证,因此它似乎可以很好地接受它。

希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接