I have a User entity that has a role prop:
@Prop({ type: Types.ObjectId, ref: 'Roles' })
role: Role | Types.ObjectId;
Role type:
export interface Role {
_id: Types.ObjectId;
name: string;
permissions: Permission[] | Types.ObjectId[];
}
Query to get users:
async getUsers(body: EntitiesGetDto): Promise<User[]> {
return this.usersModel
.find(body.filter)
.skip(body.offset)
.limit(body.limit)
.populate('role')
.sort(body.sort ?? {});
}
How can I get users filtered by role? (by role._id or role.name)
If you are using 2 different Models and schemas try using aggregate lookup, instead of using populate. Replace the query fields to match your use case:
// initiate the aggregate func
const aggr = this.userModel.aggregate();
// filter by user fields
aggr.match(body.filter);
// add lookup to match with the roles schema
aggr.append(
[{ $lookup: {
from: "role",
localField: "user_role",
foreignField: "user_role",
as: "roles"
}
},
// match the requested fields
{ $match: { '$roles.name': "..some name.." } },
// return the relevant data from the Model
{ $project: {
_id: 1,
role_name: '$roles.name',
user_field3: 1,
user_field4: 1,
}
}
]);