gpt4 book ai didi

mongodb - Mongoose 模式中的嵌套 map

转载 作者:可可西里 更新时间:2023-11-01 10:46:15 29 4
gpt4 key购买 nike

我目前正在为我们的新 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.

为什么我不能按预期嵌套 map ?是否有可能在 mongoose 模式中转换这种“规范化数组”结构,如果可以,如何转换?

感谢阅读!

最佳答案

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

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

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

我确实也从 ChildSchema 上的 mongoose 触发了验证,所以它似乎接受它就好了。

希望对您有所帮助。

关于mongodb - Mongoose 模式中的嵌套 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51762061/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com