首页 > 解决方案 > Typescript Mongoose 在 VS Code 中获取 Schema 字段的 IntelliSense 或警告

问题描述

我想为我的 Mongoose 模型设置代码完成。

因此,如果我创建一个新模型,我想查看在我的 Mongoose Schema 中定义的可用字段。编译器的错误/警告,并非所有字段都提供会很好

简单示例

//define Schema
const MyUserSchema = new Schema({
    name: String,
    firstname: String,
    password: String
})

//create Model
export const MyUserModel = model('user', MyUserSchema)

//instance of MyUserModel
let testUser = new MyUserModel({
    //want IntelliSense for fields here
    name: "Lastname",
    firstname: "Firstname",
    password: "securepassword"
}):

我想我必须以某种方式使用接口。但我不知道如何使用它们。

标签: typescriptmongoosevisual-studio-code

解决方案


由于您使用的是 TypeScript 和 JS 环境,因此您可以在 d.ts 文件中进行一些更改以在创建模型时实现自动完成。

  1. node_modules/@types/mongoose/index.d.ts
  2. 查找Model(@types/mongoose=5.5.34 中的 2881 行)的定义
  3. 做一些改变

    new(doc?: any): T;

    new(doc?: Omit<T, keyof Document>): T;

自动完成工作:)


推荐阅读