【问题标题】:Class don't understand Mongoose Model using typescript类不理解使用 typescript 的 Mongoose 模型
【发布时间】:2020-03-10 21:42:26
【问题描述】:

给出一个类型错误,他不理解 UserInterface 里面的查找,这个错误:Property 'find' does not exist on type 'UserInterface'


import User, { UserInterface } from '../schemas/User';

class UserController {
  public user: UserInterface;

  constructor() {
    this.user = new User();
  }

  public async index(req: Request, res: Response): Promise<Response> {
    const users = await this.user.find();
    return res.json(users);
  }
}

export default new UserController();

export interface UserInterface extends Document {
  email?: string;
  firstName?: string;
  lastName?: string;
}

const UserSchema = new Schema(
  {
    email: String,
    firstName: String,
    lastName: String,
  },
  {
    timestamps: true,
  },
);

export default model<UserInterface>('User', UserSchema);

【问题讨论】:

  • 这些方法可能由model&lt;UserInterface&gt; 提供,您将其导入为User。尝试将user: UserInterface 更改为user: User
  • 此错误:“用户”指的是一个值,但在此处用作类型。ts(2749)
  • 试试user: typeof User
  • 我知道了,不过现在不取用户字段的类型了哈哈。

标签: javascript node.js typescript mongoose


【解决方案1】:

而不是调用

const users = await this.user.find();

尝试调用

const users = await User.find();

看起来您正在尝试查找所有用户。

【讨论】:

  • 我尝试了这个方法,但是出现了这个错误:Expected 'this' to be used by class async method 'index'
  • 这听起来像是 eslint/tslint 失败,而不是错误
  • 是的,但我想使用 'this',如果没有选择我删除 eslint
猜你喜欢
  • 2021-10-17
  • 2021-03-19
  • 2019-01-13
  • 1970-01-01
  • 2021-06-22
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多