【问题标题】:Nested maps in mongoose schema猫鼬模式中的嵌套地图
【发布时间】:2019-01-16 15:01:59
【问题描述】:

我目前正在为我们的新 JSON 格式创建一个合适的猫鼬模式。 它不是很复杂,但我遇到了某些值没有保存为数组而是像这样的“标准化数组”的问题:

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

对象本身也可以有嵌套的“标准化数组”。

现在我尝试在顶级架构中使用猫鼬类型“地图”,如下所示:

 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.

为什么我不能按预期嵌套地图?甚至可以在猫鼬模式中投影这种“标准化数组”结构,如果可以,如何?

感谢阅读!

【问题讨论】:

  • 你找到答案了吗?我已经完成了相同的用例。

标签: mongodb mongoose mongoose-schema


【解决方案1】:

我也遇到了同样的情况,它似乎对我有用:

const ChildSchema = new Schema({
  firstName: String,
});

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

我也得到了 ChildSchema 上 mongoose 触发的验证,所以它似乎可以接受它。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2015-09-21
    • 2014-06-22
    • 2017-01-28
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2019-07-20
    • 2017-06-12
    相关资源
    最近更新 更多