首页 文章

mongoose模式中的嵌套映射

提问于
浏览
1

我正在为我们的新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
}

“回答”是一个单独的mongoose.Schema本身 . 但我得到的只是:

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

为什么我不能按预期嵌套 Map ?甚至可以在mongoose模式中投射这个“规范化数组”结构,如果是这样,怎么样?

感谢阅读!

1 回答

  • 0

    我处于相同的情况,似乎对我有用:

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

    我也从ChildSchema上获得了mongoose触发的验证,所以它似乎接受它就好了 .

    希望能帮助到你 .

相关问题