猫鼬上的打字稿界面填充

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

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;
}

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

l595511699 回答:猫鼬上的打字稿界面填充

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

您可以在接口上使用| (or) 语句,这将解决可能出现的tslint 错误的问题

所以我的用户界面会变成

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

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

本文链接:https://www.f2er.com/5674.html

大家都在问