【问题标题】:Typescript interface on mongoose populate猫鼬填充上的打字稿界面
【发布时间】:2021-08-02 19:41:38
【问题描述】:

所以我有这个猫鼬模型如下:

const userSchema: mongoose.Schema = new mongoose.Schema(
    {
        _id: String,
        email: {
            type: String,
            required: true,
        },
        firstName: String,
        lastName: String,       
        phoneNumber: String,
        cmt: {
            type: String,
            ref: 'Cmt',
        },      
    },  
);

您可以看到 cmt 字段指向另一个名为 Cmt 的模型,我将使用它的详细信息 populate

现在在另一个实例上,我需要传入 cmt id 以将其与 userSchema 链接

但那时我会收到"Type 'string' is not assignable to type 'ICmt'." 的打字稿错误

ICmt是Cmt的接口定义。

用户模式界面如下。

export interface IUser {
    _id: string;
    email: string;
    firstName: string;
    lastName: string;
    phoneNumber: string;
    cmt: ICmt;
    createdAt?: Date;
    updatedAt?: Date;
}

如何在不搞乱填充查询和创建查询的情况下修复此错误?

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    这是一个简单的解决方案,但我错了。

    可以在界面上使用|(or)语句,解决可能出现的tslint错误问题

    所以我的用户界面会变成

    export interface IUser {
        _id: string;
        email: string;
        firstName: string;
        lastName: string;
        phoneNumber: string;
        cmt: ICmt | string;
        createdAt?: Date;
        updatedAt?: Date;
    }
    

    所以我不再需要担心 tslint 错误或 tsignore

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 2020-04-30
      • 2016-02-05
      • 2020-05-11
      • 2017-04-11
      • 2016-04-01
      • 1970-01-01
      • 2021-05-06
      • 2021-01-05
      相关资源
      最近更新 更多