Code Monkey home page Code Monkey logo

typegoose's Introduction

Typegoose

(These badges are from typegoose:master)
Node.js Tests Coverage Status npm

Define Mongoose models using TypeScript classes

Basic usage

import { prop, getModelForClass } from '@typegoose/typegoose';
import * as mongoose from 'mongoose';

class User {
  @prop()
  public name?: string;

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

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

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

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

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

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:

interface Car {
  model?: string;
}

interface Job {
  title?: string;
  position?: string;
}

interface User {
  name?: string;
  age!: number;
  job?: Job;
  car?: Car | string;
  preferences?: string[];
}

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

const UserModel = mongoose.model('User', {
  name: String,
  age: { type: Number, required: true },
  job: {
    title: String;
    position: String;
  },
  car: { type: Schema.Types.ObjectId, ref: 'Car' },
  preferences: [{ type: String }]
});

You can just write this:

class Job {
  @prop()
  public title?: string;

  @prop()
  public position?: string;
}

class Car {
  @prop()
  public model?: string;
}

class User {
  @prop()
  public name?: string;

  @prop({ required: true })
  public age!: number;

  @prop()
  public job?: Job;

  @prop({ ref: () => Car })
  public car?: Ref<Car>;

  @prop({ type: () => [String] })
  public preferences?: string[];
}

Extra Examples


Requirements

  • TypeScript 3.9+
  • Node 10.15+
  • mongoose ^5.10.4
  • experimentalDecorators and emitDecoratorMetadata must be enabled in tsconfig.json
  • tsconfig option target being ES6

Note: it is recommended to not use babel see here why

Install

npm i -s @typegoose/typegoose # install typegoose itself

npm i -s mongoose # install peer-dependencie mongoose
npm i -D @types/mongoose # install all types for mongoose - this is required for typegoose to work in typescript

Testing

npm i -D
npm test

Versioning

This Project should comply with Semver. It uses the Major.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

Here are the known-issues

FAQ

Here is the FAQ

Notes

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

typegoose's People

Contributors

hasezoey avatar szokodiakos avatar ben305 avatar dandv avatar michallytek avatar simonb12 avatar luxcium avatar rjmunro avatar b-stefan avatar afgthecat avatar ggurkal avatar bar-colu avatar ukoester avatar aljazerzen avatar yardenshoham avatar richardsimko avatar kaihaase-wd avatar captaincaius avatar andreialecu avatar megahertz avatar sakulstra avatar marcelh-gh avatar mschnee avatar 19majkel94 avatar anurbol avatar gae123 avatar pabloszx avatar nodkz avatar gitschwifty avatar vnenkpet avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.