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