Mongoose the Typescript way…?

后端 未结 14 580
遥遥无期
遥遥无期 2020-11-28 19:27

Trying to implement a Mongoose model in Typescript. Scouring the Google has revealed only a hybrid approach (combining JS and TS). How would one go about implementing the

14条回答
  •  无人及你
    2020-11-28 20:06

    Just add another way (@types/mongoose must be installed with npm install --save-dev @types/mongoose)

    import { IUser } from './user.ts';
    import * as mongoose from 'mongoose';
    
    interface IUserModel extends IUser, mongoose.Document {}
    
    const User = mongoose.model('User', new mongoose.Schema({
        userName: String,
        password: String,
        // ...
    }));
    

    And the difference between interface and type, please read this answer

    This way has a advantage, you can add Mongoose static method typings:

    interface IUserModel extends IUser, mongoose.Document {
      generateJwt: () => string
    }
    

提交回复
热议问题