简体   繁体   中英

Mongoose sub-documents inside nested object

I have a schema which uses multiple fields as reference to other collections in the database.

Everything seems to work fine except for a sub-document which is present in a nested object.

When I try to add the document as a reference to that particular key ( role ) in a nested object ( metadata ), instead of the ObjectId the entire object gets saved.

This is my schema:

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[];
}

I'm using "@nestjs/mongoose": "^9.2.1" and "mongoose": "^6.8.2" .

If you want to embed a reference to the document in metadata collection, you should refer it by the objectId in the User document itself.

@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;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM