1

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".

Unknown User
  • 3,598
  • 9
  • 43
  • 81

1 Answers1

0

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;
}
Destructor
  • 523
  • 1
  • 3
  • 13