簡體   English   中英

Mongoose 子文檔里面嵌套 object

[英]Mongoose sub-documents inside nested object

我有一個模式,它使用多個字段作為對數據庫中其他 collections 的引用。

除了嵌套 object 中存在的子文檔外,一切似乎都運行良好。

當我嘗試將文檔添加為對嵌套 object( metadata )中特定鍵( role )的引用時,而不是 ObjectId,整個 object 都會被保存。

這是我的模式:

class Metadata {
  // THIS DOES NOT WORK FINE AND IT STORES THE COMPLETE OBJECT
  // AND ALSO EMPTY ARRAY IS NOT CREATED UPON THE DOCUMENT CREATION
  // WHICH IS DEFAULT BEHAVIOUR OF MONGOOSE
  @Prop({
    ref: 'Role',
    type: [mongoose.Schema.Types.ObjectId]
  })
  roles: Role[];
}

@Schema({...})
export class User {
  @Prop()
  name: string;

  @Prop()
  password: string;

  // This works fine and it only stores the ObjectId
  @Prop({
    ref: 'Favourite',
    type: [mongoose.Schema.Types.ObjectId]
  })
  favourties: Favourite[]

  @Prop({type: Metadata})
  metadata: Metadata;

  // WHEN THE SAME IS REMOVED OUT OF METADATA OBJECT, IT WORKS
  // FINE AND STORES ONLY OBJECT ID
  @Prop({
    ref: 'Role',
    type: [mongoose.Schema.Types.ObjectId]
  })
  roles: Role[];
}

我正在使用"@nestjs/mongoose": "^9.2.1""mongoose": "^6.8.2"

如果要在元數據集合中嵌入對文檔的引用,則應通過User文檔本身中的objectId引用它。

@Schema({collection: 'metadata'})
class Metadata {
  @Prop({
    ref: 'Role',
    type: [mongoose.Schema.Types.ObjectId]
  })
  roles: Role[];
}

@Schema({...})
export class User {
  @Prop()
  name: string;

  @Prop()
  password: string;

  @Prop({
    ref: 'Favourite',
    type: [mongoose.Schema.Types.ObjectId]
  })
  favourties: Favourite[]

  @Prop({
    ref: 'Metadata',
    type: [mongoose.Schema.Types.ObjectId]
  })
  metadata: Metadata;
}

暫無
暫無

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

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