I'm encountering an issue with typing in TypeScript when working with mongoose schemas. Here is the model I have for a user :
export interface IUser extends mongoose.Document {
firstname: string;
lastname: string;
email: string;
password?: string;
lang: string;
color: string;
roles: IRole[];
labs: ILab[];
}
export const UserSchema = new mongoose.Schema({
firstname: {
type: String,
required: [true, 'Firstname required']
},
lastname: {
type: String,
required: [true, 'Lastname required']
},
email: {
type: String,
required: [true, 'Email required']
},
password: {
type: String,
required: [true, 'Password required']
},
lang: {
type: String,
required: [true, 'Lang required']
},
color: {
type: String,
required: [true, 'Color required']
},
roles: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Role'
}
],
labs: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Lab'
}
]
});
My challenge comes when trying to query and retrieve all users that match a specific lab ID using this code:
User.find({ labs: { $in: req.params.id } })
However, TypeScript throws an error because the find method expects an ObjectId array, but the interface references ILab[]. The workaround I found was to use 'any' as the type, but I am aware that it's not ideal to rely on any type. If anyone has any suggestions or hints on how to address this issue, I would greatly appreciate it.