繁体   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