mongodb 嵌套对象内的Mongoose子文档

xuo3flqw  于 2023-02-03  发布在  Go
关注(0)|答案(1)|浏览(230)

我有一个模式,它使用多个字段作为对数据库中其他集合的引用。
除了嵌套对象中存在的子文档外,一切似乎都工作正常。
当我尝试将文档作为对嵌套对象(metadata)中特定键(role)的引用添加时,保存的不是ObjectId,而是整个对象。
这是我的模式:

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"

14ifxucb

14ifxucb1#

如果要在元数据集合中嵌入对文档的引用,则应通过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;
}

相关问题