Typescript猫鼬在VS Code中获得Schema字段的IntelliSense或警告

时间:2019-01-31 21:20:05

标签: typescript mongoose visual-studio-code

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

因此,如果我创建一个新模型,我想查看在Mongoose模式中定义的可用字段。还有编译器的错误/警告,那就是不是所有字段都可以提供

简单示例

//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"
}):

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

2 个答案:

答案 0 :(得分:1)

很遗憾,the Mongoose Model type accepts any in its constructor。因此,您不会因缺少字段而收到编译器错误。

也就是说,以下内容将满足您的部分要求:

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

interface User {
    name: String,
    firstname: String,
    password: String
}

interface UserModel extends User, Document { }

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

export const MyUserModel = model<UserModel>('user', MyUserSchema)

let testUser = new MyUserModel({
    name: 'foo',
    firstname: 'bar',
    password: 'baz'
});

通过上述设置,当您插入testUser时,您会在智能感知中看到namefirstnamepassword

答案 1 :(得分:0)

这并不完全符合您的期望。但是,如果您只想获取智能感知,则可以使用一种解决方法。我觉得这就是您的要求。

//Define interface
interface User {
  name: String;
  firstname: String;
  password: String;
}

interface UserModel extends User, mongoose.Document {}

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

//create Model
export const MyUserModel = mongoose.model<UserModel>('user', MyUserSchema);

let input: Partial<UserModel> = {
  //Get your intellisense here
  name: 'Lastname',
  firstname: 'Firstname',
  password: 'securepassword',
};

//instance of MyUserModel
let testUser = new MyUserModel(input);

testUser.firstname //get your intellisense here as well