簡體   English   中英

mongodb 模式中具有不同 object 類型的數組

[英]Array with different object types in mongodb's schema

我正在使用 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" }
       ]
});

所以 typescript 中的 object 類型將是

content: Array<VideosType | GamesType>

知道我該怎么做嗎?

您可以使用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

它對我有用

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],
    },
  ],
});

我不知道是否正在進行類型檢查,但是,它關閉了我的需求

  1. 顯示方案的使用情況
  2. 實體在代碼中的類型化使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM