如何在 TypeScript 中输入 mongoose ObjectID 数组

3

我在 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[]相关联。

我唯一找到的方法是将查询设置为任何类型,但是你可能知道使用任何类型并不理想。如果有人能够提供提示,那就太好了。


1
你能试试这个代码吗:labs: string[] | mongoose.Types.ObjectId[] | ILab[]; - turivishal
你会将密码以明文形式存储吗? - Wernfried Domscheit
它仍然在TS中给了我一个类型错误,我发现的唯一方法是将查询设置为任何或我的实验室设置为ObjectId [],但是这样做我无法正确操作实验室的数据。当然,我不会明文存储密码。 - François MILHET
1个回答

4
也许只需要:
import { Schema } from "mongoose";
interface IUser extends mongoose.Document {
  ...
  labs: [{ type: mongoose.Schema.Types.ObjectId, ref: "Lab" }];
}

我曾经遇到同样的问题,我是用以下方法解决的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接