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.
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
content: Array<VideosType | GamesType>
any idea how can i do this?
You can use 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.