TS 中文文档 TS 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • 入门教程

    • TypeScript 手册
    • 基础知识
    • 日常类型
    • 类型缩小
    • 更多关于函数
    • 对象类型
    • 从类型创建类型
    • 泛型
    • Keyof 类型运算符
    • Typeof 类型运算符
    • 索引访问类型
    • 条件类型
    • 映射类型
    • 模板字面类型
    • 类
    • 模块
  • 参考手册

  • 项目配置

This Repository got moved


Please use hasezoey's fork to be up-to-date Please dont create new issues & pull request anymore, thanks

Typegoose


Define Mongoose models using TypeScript classes.

Basic usage


  1. ``` ts
  2. import { prop, Typegoose, ModelType, InstanceType } from 'typegoose';
  3. import * as mongoose from 'mongoose';

  4. mongoose.connect('mongodb://localhost:27017/test');

  5. class User extends Typegoose {
  6.   @prop()
  7.   name?: string;
  8. }

  9. const UserModel = new User().getModelForClass(User);

  10. // UserModel is a regular Mongoose Model with correct types
  11. (async () => {
  12.   const u = await UserModel.create({ name: 'JohnDoe' });
  13.   const user = await UserModel.findOne();

  14.   // prints { _id: 59218f686409d670a97e53e0, name: 'JohnDoe', __v: 0 }
  15.   console.log(user);
  16. })();
  17. ```

Motivation


A common problem when using Mongoose with TypeScript is that you have to define both the Mongoose model and the TypeScript interface. If the model changes, you also have to keep the TypeScript interface file in sync or the TypeScript interface would not represent the real data structure of the model.

Typegoose aims to solve this problem by defining only a TypeScript interface (class) which need to be enhanced with special Typegoose decorators.

Under the hood it uses the reflect-metadata API to retrieve the types of the properties, so redundancy can be significantly reduced.

Instead of:

  1. ``` ts
  2. interface Car {
  3.   model?: string;
  4. }

  5. interface Job {
  6.   title?: string;
  7.   position?: string;
  8. }

  9. interface User {
  10.   name?: string;
  11.   age: number;
  12.   job?: Job;
  13.   car: Car | string;
  14. }

  15. mongoose.model('User', {
  16.   name: String,
  17.   age: { type: Number, required: true },
  18.   job: {
  19.     title: String;
  20.     position: String;
  21.   },
  22.   car: { type: Schema.Types.ObjectId, ref: 'Car' }
  23. });

  24. mongoose.model('Car', {
  25.   model: string,
  26. });
  27. ```

You can just:

  1. ``` ts
  2. class Job {
  3.   @prop()
  4.   title?: string;

  5.   @prop()
  6.   position?: string;
  7. }

  8. class Car extends Typegoose {
  9.   @prop()
  10.   model?: string;
  11. }

  12. class User extends Typegoose {
  13.   @prop()
  14.   name?: string;

  15.   @prop({ required: true })
  16.   age!: number;

  17.   @prop()
  18.   job?: Job;

  19.   @prop({ ref: Car })
  20.   car?: Ref<Car>;
  21. }
  22. ```

Please note that sub documents do not have to extend Typegoose. You can still give them default value in prop decorator, but you can't create static or instance methods on them.

Requirements


TypeScript 3.2+
Node 8+
mongoose 5+
emitDecoratorMetadata and experimentalDecorators must be enabled in tsconfig.json
reflect-metadata must be installed

Install


npm install typegoose -S

You also need to install mongoose and reflect-metadata, in versions < 5.0, these packages were listed as dependencies in package.json, starting with version 5.0 these packages are listed as peer dependencies.

npm install mongoose reflect-metadata -S

Testing


npm test

Versioning


Major.Minor.Fix (or how npm expresses it Major.Minor.Patch )

0.0.x is for minor fixes, like hot-fixes
0.x.0 is for Minor things like adding features, that are non-breaking (or at least should not be breaking anything)
x.0.0 is for Major things like adding features that are breaking or refactoring which is a breaking change
0.0.0-x is for a Pre-Release, that are not yet ready to be published

API Documentation


Typegoose class


This is the class which your schema defining classes must extend.

Methods:


getModelForClass<T>(t: T, options?: GetModelForClassOptions)

This method returns the corresponding Mongoose Model for the class (T ). If no Mongoose model exists for this class yet, one will be created automatically (by calling the method setModelForClass ).

setModelForClass<T>(t: T, options?: GetModelForClassOptions)

This method assembles the Mongoose Schema from the decorated schema defining class, creates the Mongoose Model and returns it. For typing reasons, the schema defining class must be passed down to it.

Hint: If a Mongoose Model already exists for this class, it will be overwritten.

The GetModelForClassOptions provides multiple optional configurations:

existingMongoose: mongoose : An existing Mongoose instance can also be passed down. If given, Typegoose uses this Mongoose instance's model methods.
schemaOptions: mongoose.SchemaOptions : Additional schema options can be passed down to the schema-to-be-created.
existingConnection: mongoose.Connection : An existing Mongoose connection can also be passed down. If given, Typegoose uses this Mongoose instance's model methods.

Property decorators


Typegoose comes with TypeScript decorators, which responsibility is to connect the Mongoose schema behind the TypeScript class.

prop(options)


The prop decorator adds the target class property to the Mongoose schema as a property. Typegoose checks the decorated property's type and sets the schema property accordingly. If another Typegoose extending class is given as the type, Typegoose will recognize this property as a sub document.

The options object accepts multiple config properties:

required : Just like the Mongoose required it accepts a handful of parameters. Please note that it's the developer's responsibility to make sure that if required is set to false then the class property should be optional.

Note: for coding style (and type completion) you should use ! when it is marked as required

  1. ``` ts
  2. // this is now required in the schema
  3. @prop({ required: true })
  4. firstName!: string;

  5. // by default, a property is not required
  6. @prop()
  7. lastName?: string; // using the ? optional property
  8. ```

index : Tells Mongoose whether to define an index for the property.

  1. ``` ts
  2. @prop({ index: true })
  3. indexedField?: string;
  4. ```

unique : Just like the Mongoose unique, tells Mongoose to ensure a unique index is created for this path.

  1. ``` ts
  2. // this field is now unique across the collection
  3. @prop({ unique: true })
  4. uniqueId?: string;
  5. ```

enum : The enum option accepts a string array. The class property which gets this decorator should have an enum-like type which values are from the provided string array. The way how the enum is created is delegated to the developer, Typegoose needs a string array which hold the enum values, and a TypeScript type which tells the possible values of the enum. However, if you use TS 2.4+, you can use string enum as well.

  1. ``` ts
  2. enum Gender {
  3.   MALE = 'male',
  4.   FEMALE = 'female',
  5. }

  6. @prop({ enum: Gender })
  7. gender?: Gender;
  8. ```

lowercase : for strings only; whether to always call .toLowerCase() on the value.

  1. ``` ts
  2. @prop({ lowercase: true })
  3. nickName?: string;
  4. ```

uppercase : for strings only; whether to always call .toUpperCase() on the value.

  1. ``` ts
  2. @prop({ uppercase: true })
  3. nickName?: string;
  4. ```

trim : for strings only; whether to always call .trim() on the value.

  1. ``` ts
  2. @prop({ trim: true })
  3. nickName?: string;
  4. ```

default : The provided value will be the default for that Mongoose property.

  1. ``` ts
  2. @prop({ default: 'Nick' })
  3. nickName?: string;
  4. ```

_id : When false, no _id is added to the subdocument

  1. ``` ts
  2. class Car extends Typegoose {}

  3. @prop({ _id: false })
  4. car?: Car;
  5. ```

ref : By adding the ref option with another Typegoose class as value, a Mongoose reference property will be created. The type of the property on the Typegoose extending class should be Ref<T> (see Types section).

  1. ``` ts
  2. class Car extends Typegoose {}

  3. @prop({ ref: Car })
  4. car?: Ref<Car>;
  5. ```

refPath : Is the same as ref, only that it looks at the path specified, and this path decides which model to use

  1. ``` ts
  2. class Car extends Typegoose {}
  3. class Shop extends Typegoose {}

  4. // in another class
  5. class Another extends Typegoose {
  6.   @prop({ required: true, enum: 'Car' | 'Shop' })
  7.   which!: string;

  8.   @prop({ refPath: 'which' })
  9.   kind?: Ref<Car | Shop>;
  10. }
  11. ```

min / max (numeric validators): Same as Mongoose numberic validators.

  1. ``` ts
  2. @prop({ min: 10, max: 21 })
  3. age?: number;
  4. ```

minlength / maxlength / match (string validators): Same as Mongoose string validators.

  1. ``` ts
  2. @prop({ minlength: 5, maxlength: 10, match: /[0-9a-f]*/ })
  3. favouriteHexNumber?: string;
  4. ```

validate (custom validators): You can define your own validator function/regex using this. The function has to return a boolean or a Promise (async validation).

  1. ``` ts
  2. // you have to get your own `isEmail` function, this is a placeholder

  3. @prop({ validate: (value) => isEmail(value)})
  4. email?: string;

  5. // or

  6. @prop({ validate: (value) => { return new Promise(res => { res(isEmail(value)) }) })
  7. email?: string;

  8. // or

  9. @prop({ validate: {
  10.     validator: val => isEmail(val),
  11.     message: `{VALUE} is not a valid email`
  12. }})
  13. email?: string;

  14. // or

  15. @prop({ validate: /\S+@\S+\.\S+/ })
  16. email?: string;

  17. // you can also use multiple validators in an array.

  18. @prop({ validate:
  19.   [
  20.     {
  21.         validator: val => isEmail(val),
  22.         message: `{VALUE} is not a valid email`
  23.     },
  24.     {
  25.         validator: val => isBlacklisted(val),
  26.         message: `{VALUE} is blacklisted`
  27.     }
  28.   ]
  29. })
  30. email?: string;
  31. ```

alias (alias): Same as Mongoose Alias, only difference is the extra property for type completion

  1. ``` ts
  2. class Dummy extends Typegoose {
  3.   @prop({ alias: "helloWorld" })
  4.   public hello: string; // will be included in the DB
  5.   public helloWorld: string; // will NOT be included in the DB, just for type completion (gets passed as hello in the DB)
  6. }
  7. ```

Mongoose gives developers the option to create virtual properties. This means that actual database read/write will not occur these are just 'calculated properties'. A virtual property can have a setter and a getter. TypeScript also has a similar feature which Typegoose uses for virtual property definitions (using the prop decorator).

  1. ``` ts
  2. @prop()
  3. firstName?: string;

  4. @prop()
  5. lastName?: string;

  6. @prop() // this will create a virtual property called 'fullName'
  7. get fullName() {
  8.   return `${this.firstName} ${this.lastName}`;
  9. }
  10. set fullName(full) {
  11.   const [firstName, lastName] = full.split(' ');
  12.   this.firstName = firstName;
  13.   this.lastName = lastName;
  14. }
  15. ```

TODO: add documentation for virtual population

arrayProp(options)


The arrayProp is a prop decorator which makes it possible to create array schema properties.

The options object accepts required, enum and default, just like the prop decorator. In addition to these the following properties exactly one should be given:

items : This will tell Typegoose that this is an array which consists of primitives (if String, Number, or other primitive type is given) or this is an array which consists of subdocuments (if it's extending the Typegoose class).

  1. ``` ts
  2. @arrayProp({ items: String })
  3. languages?: string[];
  4. ```

Note that unfortunately the reflect-metadata API does not let us determine the type of the array, it only returns Array when the type of the property is queried. This is why redundancy is required here.

itemsRef : In mutual exclusion with items, this tells Typegoose that instead of a subdocument array, this is an array with references in it. On the Mongoose side this means that an array of Object IDs will be stored under this property. Just like with ref in the prop decorator, the type of this property should be Ref<T>[].

  1. ``` ts
  2. class Car extends Typegoose {}

  3. // in another class
  4. @arrayProp({ itemsRef: Car })
  5. previousCars?: Ref<Car>[];
  6. ```

itemsRefPath (IRP): Is the same as itemsRef only that it looks at the specified path of the class which specifies which model to use

  1. ``` ts
  2. class Car extends Typegoose {}
  3. class Shop extends Typegoose {}

  4. // in another class
  5. class Another extends Typegoose {
  6.   @prop({ required: true, enum: 'Car' | 'Shop' })
  7.   which!: string;

  8.   @arrayProp({ itemsRefPath: 'which' })
  9.   items?: Ref<Car | Shop>[];
  10. }
  11. ```

mapProp(options)


The mapProp is a prop decorator which makes it possible to create map schema properties.

The options object accepts enum and default, just like prop decorator. In addition to these the following properties are accepted:

of : This will tell Typegoose that the Map value consists of primitives (if String, Number, or other primitive type is given) or this is an array which consists of subdocuments (if it's extending the Typegoose class).

  1. ``` ts
  2. class Car extends Typegoose {
  3.   @mapProp({ of: Car })
  4.   public keys?: Map<string, Car>;
  5. }
  6. ```

mapDefault : This will set the default value for the map.

  1. ``` ts
  2. enum ProjectState {
  3.     WORKING = 'working',
  4.     BROKEN = 'broken',
  5.     MAINTAINANCE = 'maintainance',
  6. }

  7. class Car extends Typegoose {
  8.   @mapProp({ of: String, enum: ProjectState,mapDefault: { 'MainProject' : ProjectState.WORKING }})
  9.   public projects?: Map<string, ProjectState>;
  10. }
  11. ```

Method decorators


In Mongoose we can attach two types of methods for our schemas: static (model) methods and instance methods. Both of them are supported by Typegoose.

staticMethod


Static Mongoose methods must be declared with static keyword on the Typegoose extending class. This will ensure, that these methods are callable on the Mongoose model (TypeScript won't throw development-time error for unexisting method on model object).

If we want to use another static method of the model (built-in or created by us) we have to override the this in the method using the type specifying of this for functions. If we don't do this, TypeScript will throw development-time error on missing methods.

  1. ``` ts
  2. @staticMethod
  3. static findByAge(this: ModelType<User> & typeof User, age: number) {
  4.   return this.findOne({ age });
  5. }
  6. ```

Note that the & typeof T is only mandatory if we want to use the developer defined static methods inside this static method. If not then the ModelType<T> is sufficient, which will be explained in the Types section.

instanceMethod


Instance methods are on the Mongoose document instances, thus they must be defined as non-static methods. Again if we want to call other instance methods the type of this must be redefined to InstanceType<T> (see Types).

  1. ``` ts
  2. @instanceMethod
  3. incrementAge(this: InstanceType<User>) {
  4.   const age = this.age || 1;
  5.   this.age = age + 1;
  6.   return this.save();
  7. }
  8. ```

Class decorators


Mongoose allows the developer to add pre and post hooks / middlewares to the schema. With this it is possible to add document transformations and observations before or after validation, save and more.

Typegoose provides this functionality through TypeScript's class decorators.

pre


We can simply attach a @pre decorator to the Typegoose class and define the hook function like you normally would in Mongoose. (Method supports REGEXP)

  1. ``` ts
  2. @pre<Car>('save', function(next) { // or @pre(this: Car, 'save', ...
  3.   if (this.model === 'Tesla') {
  4.     this.isFast = true;
  5.   }
  6.   next();
  7. })
  8. class Car extends Typegoose {
  9.   @prop({ required: true })
  10.   model!: string;
Last Updated: 2023-09-03 17:10:52