Mongoose the Typescript way…?

后端 未结 14 575
遥遥无期
遥遥无期 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:08

    Here's a strong typed way to match a plain model with a mongoose schema. The compiler will ensure the definitions passed to mongoose.Schema matches the interface. Once you have the schema, you can use

    common.ts

    export type IsRequired =
      undefined extends T
      ? false
      : true;
    
    export type FieldType =
      T extends number ? typeof Number :
      T extends string ? typeof String :
      Object;
    
    export type Field = {
      type: FieldType,
      required: IsRequired,
      enum?: Array
    };
    
    export type ModelDefinition = {
      [P in keyof M]-?:
        M[P] extends Array ? Array> :
        Field
    };
    

    user.ts

    import * as mongoose from 'mongoose';
    import { ModelDefinition } from "./common";
    
    interface User {
      userName  : string,
      password  : string,
      firstName : string,
      lastName  : string,
      email     : string,
      activated : boolean,
      roles     : Array
    }
    
    // The typings above expect the more verbose type definitions,
    // but this has the benefit of being able to match required
    // and optional fields with the corresponding definition.
    // TBD: There may be a way to support both types.
    const definition: ModelDefinition = {
      userName  : { type: String, required: true },
      password  : { type: String, required: true },
      firstName : { type: String, required: true },
      lastName  : { type: String, required: true },
      email     : { type: String, required: true },
      activated : { type: Boolean, required: true },
      roles     : [ { type: String, required: true } ]
    };
    
    const schema = new mongoose.Schema(
      definition
    );
    

    Once you have your schema, you can use methods mentioned in other answers such as

    const userModel = mongoose.model('User', schema);
    

提交回复
热议问题