typescript 类型“”(文档〈未知、任意、IUser>& IUser & { _id:对象ID; })|零'

bfrts1fy  于 2023-02-25  发布在  TypeScript
关注(0)|答案(1)|浏览(131)

我是TypeScript的新手,在我的express和MongoDB应用程序上遇到了这个错误。
这是我的User.ts模型。

import mongoose from "mongoose";

interface IUser  {
    username: string;
    password: string;
    email: string;
    isAdmin: boolean;
  }

const userSchema = new mongoose.Schema<IUser>(
    {
        username: {
            type: String,
            required: true,
            unique: true,
            minlength: 3
        },
        email: {
            type: String,
            required: true,
            unique: true,
        },
        password: {
            type: String,
            required: true
        },
        isAdmin: {
            type: Boolean,
            default: false,
        }
    },
    {
        timestamps: true,
    }
)

export const UserModel = mongoose.model<IUser>("User", userSchema);

这是我的路线,当我试图访问密码时,我会得到错误。

router.get( "/:id", verifyToken, async (req: any, res: any) => {
    const user = await User.findById(req.params.id);
    if (!user) {
        res.status(404).json({ message: "User not found" });
    }

    const {password, ...other} = user;

    res.status(200).json(other);
}
)

完整错误:

TSError: ⨯ Unable to compile TypeScript:
routes/user.ts:28:12 - error TS2339: Property 'password' does not exist on type '(Document<unknown, any, IUser> & IUser & { _id: ObjectId; }) | null'.

28     const {password, ...other} = user;

我正在做他们docs中所说的事情,所以我有点不知所措。

nue99wik

nue99wik1#

const user: IUser | null = await User.findById(req.params.id);

我必须定义变量user。

相关问题