我在 TypeScript 和 mongoose schema 中遇到了输入问题。以下是我为用户定义的模型:
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'
}
]
});
事实上,我想执行一个查询以检索与特定实验室ID匹配的所有用户,因此我写了这个查询语句:
User.find({ labs: { $in: req.params.id } })
但是我在使用TypeScript时遇到了一个错误,因为find实际上在ObjectId数组上,但是在接口中与ILab[]相关联。
我唯一找到的方法是将查询设置为任何类型,但是你可能知道使用任何类型并不理想。如果有人能够提供提示,那就太好了。
labs: string[] | mongoose.Types.ObjectId[] | ILab[];
- turivishal