[英]Mongoose Schema with different objects
I have a base schema that looks like that:我有一个看起来像这样的基本架构:
let Entry = new Schema({
key: String,
items: [
{
id: Number,
text: String
}
]});
But the item schema can vary, I want that I can append new object that have the same schema like the the base schema.但是项目架构可能会有所不同,我希望我可以 append 新 object 具有与基本架构相同的架构。 So that an object in items can also have own items.
这样物品中的 object 也可以拥有自己的物品。 Example:
例子:
let Entry = new Schema({
key: String,
items: [
{
id: Number,
text: String
},
{
key: String,
items: [
...
]
}
]
});
And so on... so that I can have maybe 4 normal item objects with id
and text
, or maybe also nested objects in items
, which again have key
and items[...]
properties, with the possibility to repeat the process even further.依此类推...这样我就可以拥有 4 个带有
id
和text
的普通 item 对象,或者也可以拥有items
中的嵌套对象,它们再次具有key
和items[...]
属性,甚至可以重复该过程更远。
One method would be to utilise the Mixed type from Mongoose.一种方法是使用 Mongoose 中的混合类型。
Say something like this:说这样的话:
let Entry = new Schema({
key: String,
items: [
{
id: Number,
text: String,
data: {
type: Schema.Types.Mixed,
default: {}
}
}
]});
Now this example places any 'custom' fields inside a data property, unsure if that would suffice for your needs.现在,此示例将任何“自定义”字段放在数据属性中,不确定这是否足以满足您的需求。
Usage用法
const newEntry = new Entry({
id: 1,
text: "foobar",
data: {
hello: "world",
isCorrect: true
}
});
Alternatively, you could just set strict to false on the schema.或者,您可以在架构上将 strict 设置为 false。
let Entry = new Schema({
key: String,
items: [
{
id: Number,
text: String
}
]}, { strict: false});
Usage用法
const newEntry = new Entry({
id: 1,
text: "foobar",
hello: "world",
isCorrect: true
});
My personal preference would be the first option, at least this way, looking at the schema, I know that there is a mixed 'bag' of data in each record, contained within the 'data' field.我个人的偏好是第一个选项,至少这样,查看架构,我知道每条记录中都有一个混合的数据“包”,包含在“数据”字段中。 Both are documented methods defined within the mongoose documentation, and hence perfectly valid.
两者都是 mongoose 文档中定义的记录方法,因此完全有效。 Pick your poison:)
选择你的毒药:)
Refs:参考:
Mixed Schema Type documentation:混合模式类型文档:
https://mongoosejs.com/docs/schematypes.html#mixed https://mongoosejs.com/docs/schematypes.html#mixed
strict Schema option documentation:严格的 Schema 选项文档:
https://mongoosejs.com/docs/guide.html#strict https://mongoosejs.com/docs/guide.html#strict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.