类型“文档"缺少类型中的以下属性 [英] Type 'Document' is missing the following properties from type

查看:55
本文介绍了类型“文档"缺少类型中的以下属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 Node/w Typescript REST API,我有一个注册方法,它创建一个用户并使用创建的用户 firstName、lastName、email 进行响应.

So I have a Node /w Typescript REST API, I have signup method which creates a user and responses with the created users firstName, lastName, email.

问题是我遇到了这个打字稿错误,提示类型‘文档’缺少‘SavedUser’类型中的以下属性:firstName、lastName、email".

The problem is I am having this typescript error that says "Type 'Document' is missing the following properties from type 'SavedUser': firstName, lastName, email".

我相信在我的 SavedUser 界面中添加 mongoose.Document 类型会有所帮助,我不确定,谢谢您的帮助!

I believe its something with adding mongoose.Document type in my SavedUser Interface, i am not sure tho, thanks for the help!

错误截图:

示例代码:

    interface SavedUser {
        firstName: string 
        lastName: string
        email: string
    }

    ...

    public async signUp(req: Request, res: Response): Promise<void | Response> {
        const salt: string = await bcrypt.genSalt(10)
        const hashedPassword: string = await bcrypt.hash(req.body.password, salt)

        const user = new User({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            email: req.body.email,
            password: hashedPassword
        })

        try {
            const { firstName, lastName, email }: SavedUser = await user.save()

            return res.status(200).send({
                firstName,
                lastName,
                email
            })
        } catch (err) {
            return res.status(400).send(err)
        }
    }

推荐答案

我不知道问题究竟出在哪里,但这就是我使用 TypeScript 创建 mongoose 模式的方式,它对我有用.

I do not know where the problem exactly but this is how I create mongoose schema using TypeScript and it works for me.

import * as mongoose from 'mongoose';

interface SavedUserDocument extends mongoose.Document {
    firstName: string;
    lastName: string;
    email: string;
}

const SavedUserSchema = new mongoose.Schema({...});
export const SavedUser = mongoose.model<SavedUserDocument>('saveduser', SavedUserSchema);

希望它也适用于您.

这篇关于类型“文档"缺少类型中的以下属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆