【问题标题】:Property 'password' does not exist on type 'Promise<void>'类型“Promise<void>”上不存在属性“密码”
【发布时间】:2023-03-08 04:23:01
【问题描述】:

所以我正在尝试向我的网站添加登录功能,并且我正在使用带有 mognoose 的 typescript,我得到了这个Property 'password' does not exist on type 'Promise&lt;void&gt;' 错误

getUserFromLogin

const getUserFromLogin = async (email: string) => {
    await mongo().then(async mongoose => {
        try {
            const res = await UserModel.findOne({
                email,
            });

            return res;
        } finally {
            mongoose.connection.close();
        }
    });
};

用户架构:

import { Schema, model, Document } from "mongoose";

export interface IUser extends Document {
    id: string;
    username: string;
    email: string;
    password: string;
}

interface reqStringInterface {
    type: StringConstructor;
    required: boolean;
}

const reqString: reqStringInterface = {
    type: String,
    required: true,
};

const userSchema = new Schema<IUser>({
    id: reqString,
    username: reqString,
    email: reqString,
    password: reqString,
});

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

我很确定解决方法是在 getUserFromLogin 函数中添加一个返回值,但是当我添加 Promise&lt;any&gt; 时,它会抛出此错误 Property 'password' does not exist on type 'Promise&lt;any&gt;'。谢谢!

【问题讨论】:

  • getUserFromLogin 是一个 async 函数,它返回一个 promise 的......实际上,未定义的。但是一旦你做出了用户的承诺,你仍然需要在请求处理程序中解决这个问题,使用.thenawait

标签: typescript mongodb express mongoose


【解决方案1】:

问题是getUserFromLogin 不返回任何内容,因为您的return res 在箭头函数内。为了避免这种混淆,尽量不要在一个方法中混合thenawait 语法,你可以这样重写:

const getUserFromLogin = async (email: string) => {
    const mongoose = await mongo();
    try {
      const res = await UserModel.findOne({email});
      return res;
    } finally {
      mongoose.connection.close();
    }
};

然后你需要等待承诺

let user = await getUserFromLogin(email)

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 2019-02-04
    • 2019-07-23
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2019-03-18
    • 2018-08-11
    相关资源
    最近更新 更多