I am working on a NestJS backend with Mongo but I am experiencing difficulties with the mongo references.
Let me explain the situation a bit more. I have class called SystemInformation that contain fields like when was the object created or by who. All the other schema of the application extend this class. The field "createdBy" is a references to the User schema (that also extend SystemInformation). When I am saving an object the payload contain the id of the user who created the record. But when I look at the mongo database from Compass I see the field as a string, but never as a ref with the official format which look like :
{ "$ref" : <value>, "$id" : <value>, "$db" : <value> }
Here are the relevant part of the code is am using :
This is the system class and schema :
@ObjectType()
@Schema()
class SystemContent {
@Field()
@Prop({ required: true })
createdAt: number;
@Field()
@Prop({ default: 0 })
updatedAt: number;
@Field()
@Prop({ required: true, type: mongoose.Schema.Types.ObjectId, ref: 'User' })
createdBy: string;
@Field()
@Prop({ default: '' })
updatedBy: string;
}
@ObjectType()
@Schema()
export class SystemInformation {
@Field()
@Prop({ required: true })
system: SystemContent;
}
The User class as example of my extend implementation:
@Schema()
export class User extends SystemInformation {
id: string;
@Prop({ required: true, unique: true })
username: string;
@Prop({ required: true, unique: true })
email: string;
@Prop({ required: true })
hash: string;
@Prop({ default: false })
verified: boolean;
@Prop({ default: false })
enabled: boolean;
@Prop({ default: 0 })
bruteforce: number;
}
export const UserSchema = SchemaFactory.createForClass(User);
export type UserDocument = User & Document;
The payload and function that save to mongo is :
const payload = {
...
system: {
createdBy: '601c12060164023d59120cf43',
createdAt: 0,
},
};
const result = await new this.model(payload).save();
I wonder what I am doing wrong, could you guys please help me ?
but never as a ref with the official format which look like
mongoose dosnt use such an format, mongoose references work by saving the id directly as the type that it is on the target schema (objectid for objectid, string for string), and to look up which db an id is assigned, it probably uses the model on what connection & db it is created on
PS: typegoose references can be expressed with public property: Ref<TargetClass>
PPS: the official typegoose type to combine TargetClass
and Document
is called DocumentType<TargetClass>