Typegoose

Define Mongoose models using TypeScript classes

README

Typegoose


(These badges are from typegoose:master) [![Node.js Tests](https://github.com/typegoose/typegoose/workflows/Node.js%20Tests/badge.svg?branch=master)](https://github.com/typegoose/typegoose/actions?query=workflow%3A"Node.js+Tests") [![codecov.io](https://codecov.io/github/typegoose/typegoose/coverage.svg?branch=master)](https://codecov.io/github/typegoose/typegoose?branch=master) [![npm](https://img.shields.io/npm/dt/@typegoose/typegoose.svg)](https://www.npmjs.com/package/@typegoose/typegoose)

Define Mongoose models using TypeScript classes

Migration


Migration Guides:  
(Date format: dd-mm-yyyy)

- 8 to 9 (released on22-09-2021)
- 7 to 8 (released on28-07-2021)
- 6 to 7 (released on01-04-2020)
- 5 to 6 (released on30-09-2019)

Basic usage


  1. ```ts
  2. import { prop, getModelForClass } from '@typegoose/typegoose';
  3. import * as mongoose from 'mongoose';

  4. class User {
  5.   @prop()
  6.   public name?: string;

  7.   @prop({ type: () => [String] })
  8.   public jobs?: string[];
  9. }

  10. const UserModel = getModelForClass(User); // UserModel is a regular Mongoose Model with correct types

  11. (async () => {
  12.   await mongoose.connect('mongodb://localhost:27017/', { useNewUrlParser: true, useUnifiedTopology: true, dbName: 'test' });

  13.   const { _id: id } = await UserModel.create({ name: 'JohnDoe', jobs: ['Cleaner'] } as User); // an "as" assertion, to have types for all properties
  14.   const user = await UserModel.findById(id).exec();

  15.   console.log(user); // prints { _id: 59218f686409d670a97e53e0, name: 'JohnDoe', __v: 0 }
  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 needs to be enhanced with special Typegoose decorators (like @prop).

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

Instead of writing this:

  1. ```ts
  2. // This is a representation of how typegoose's compile output would look like
  3. interface Car {
  4.   model?: string;
  5. }

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

  10. interface User {
  11.   name?: string;
  12.   age!: number;
  13.   preferences?: string[];
  14.   mainJob?: Job;
  15.   jobs?: Job[];
  16.   mainCar?: Car | string;
  17.   cars?: (Car | string)[];
  18. }

  19. const JobSchema = new mongoose.Schema({
  20.   title: String;
  21.   position: String;
  22. });

  23. const CarModel = mongoose.model('Car', {
  24.   model: string,
  25. });

  26. const UserModel = mongoose.model('User', {
  27.   name: { type: String },
  28.   age: { type: Number, required: true },
  29.   preferences: [{ type: String }],
  30.   mainJob: { type: JobSchema },
  31.   jobs: [{ type: JobSchema }],
  32.   mainCar: { type: Schema.Types.ObjectId, ref: 'Car' },
  33.   cars: [{ type: Schema.Types.ObjectId, ref: 'Car' }],
  34. });
  35. ```

You can just write this:

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

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

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

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

  15.   @prop({ required: true })
  16.   public age!: number; // This is a single Primitive

  17.   @prop({ type: () => [String] })
  18.   public preferences?: string[]; // This is a Primitive Array

  19.   @prop()
  20.   public mainJob?: Job; // This is a single SubDocument

  21.   @prop({ type: () => Job })
  22.   public jobs?: Job[]; // This is a SubDocument Array

  23.   @prop({ ref: () => Car })
  24.   public mainCar?: Ref<Car>; // This is a single Reference

  25.   @prop({ ref: () => Car })
  26.   public cars?: Ref<Car>[]; // This is a Reference Array
  27. }
  28. ```



Requirements & Install



Testing


  1. ```sh
  2. yarn install
  3. yarn run test
  4. ```

Versioning


This Project should comply with Semver. It uses theMajor.Minor.Fix standard (or in NPM terms, Major.Minor.Patch).

Join Our Discord Server


To ask questions or just talk with us, join our Discord Server.

Documentation



Known Issues



FAQ



Notes


Please don't add +1 or similar comments to issues. Use the reactions instead.