[英]Array with different object types in mongodb's schema
i'm developing my application using node.js and mongoose. I have an schema called categories
and it contains a key named content
, and i need to assign it different types of object, like bellow.我正在使用 node.js 和 mongoose 开发我的应用程序。我有一个名为
categories
的模式,它包含一个名为content
的键,我需要为它分配不同类型的 object,如下所示。
const categorySchema = new Schema({
label: { type: String, required: true },
content: [
{ type: Schema.Types.ObjectId, ref: "Videos" },
{ type: Schema.Types.ObjectId, ref: "Games" }
]
});
so the object type in typescript would be所以 typescript 中的 object 类型将是
content: Array<VideosType | GamesType>
any idea how can i do this?知道我该怎么做吗?
You can use Schema.Types.Mixed
https://mongoosejs.com/docs/schematypes.html#mixed :您可以使用
Schema.Types.Mixed
https://mongoosejs.com/docs/schematypes.html#mixed :
const categorySchema = new Schema({
label: { type: String, required: true },
content: [{ type: Schema.Types.Mixed }]
});
如果你有多种类型,那么你可以创建一个混合类型的数组,它基本上可以接受数组中的任何类型。
content: Array
It worked for me它对我有用
const PriceFilterSchema = new Schema<PriceFilter>({
filterType: { type: String, required: true /* PRICE_FILTER */ },
tickSize: { type: String, required: true },
});
const LotSizeSchema = new Schema<LotSize>({
filterType: { type: String, required: true /* LOT_SIZE */ },
stepSize: { type: String, required: true },
});
//Main schema
const SymbolsSchema = new Schema<SymbolType>({
filters: [
{
type: MongooseSchema.Types.Mixed,
// Here I used enum
enum: [PriceFilterSchema, LotSizeSchema],
},
],
});
I do not know if type checking is happening, BUT, it closes my needs我不知道是否正在进行类型检查,但是,它关闭了我的需求
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.