Currently, I am developing a backend using NestJs and Typegoose, with the following models:
DEPARTMENT
@modelOptions({ schemaOptions: { collection: 'user_department', toJSON: { virtuals: true }, toObject: { virtuals: true }, id: false } })
export class Department {
@prop({ required: true })
_id: mongoose.Types.ObjectId;
@prop({ required: true })
name: string;
@prop({ ref: () => User, type: String })
public supervisors: Ref<User>[];
members: User[];
static paginate: PaginateMethod<Department>;
}
USER
@modelOptions({ schemaOptions: { collection: 'user' } })
export class User {
@prop({ required: true, type: String })
_id: string;
@prop({ required: true })
userName: string;
@prop({ required: true })
firstName: string;
@prop({ required: true })
lastName: string;
[...]
@prop({ ref: () => Department, default: [] })
memberOfDepartments?: Ref<Department>[];
static paginate: PaginateMethod<User>;
}
Regarding the relationship between users and departments, one user can be associated with multiple departments, and one department can have many members (users). To handle this scenario efficiently, I opted for one-way embedding as mentioned in this resource: Two Way Embedding vs. One Way Embedding in MongoDB (Many-To-Many). This is why the User model contains the "memberOfDepartments" array, while the Department model does not store a Member-array.
The first question arises when querying the members of a Department object by looking for users where the department._id is present in the "memberOfDepartments" array. I attempted various methods like virtual populate, but encountered issues primarily related to handling one-to-many relationships effectively within Typegoose.
The second question pertains to managing the deletion of a department and subsequently removing references to that department from associated users. While there are resources available for MongoDB and Mongoose documentation, adapting these concepts to work seamlessly with Typegoose poses challenges due to limited documentation.