Typegoose

Typegoose -- 使用 TypeScript 类定义 Mongoose 模型。「Typegoose - Define Mongoose models using TypeScript classes.」

Github stars Tracking Chart

This Repository got moved

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

Typegoose

Build Status
Coverage Status
npm

Define Mongoose models using TypeScript classes.

Basic usage

import { prop, Typegoose, ModelType, InstanceType } from 'typegoose';
import * as mongoose from 'mongoose';

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

class User extends Typegoose {
  @prop()
  name?: string;
}

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

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

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

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:

interface Car {
  model?: string;
}

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

interface User {
  name?: string;
  age: number;
  job?: Job;
  car: Car

Main metrics

Overview
Name With Ownerszokodiakos/typegoose
Primary LanguageTypeScript
Program languageTypeScript (Language Count: 1)
PlatformLinux, Mac, Windows
License:MIT License
所有者活动
Created At2017-03-17 21:50:35
Pushed At2021-05-10 22:53:43
Last Commit At2019-09-06 11:07:59
Release Count30
Last Release Namev5.9.0 (Posted on )
First Release Namev2.2.0 (Posted on 2017-07-14 17:56:43)
用户参与
Stargazers Count1.2k
Watchers Count23
Fork Count133
Commits Count285
Has Issues Enabled
Issues Count284
Issue Open Count8
Pull Requests Count79
Pull Requests Open Count10
Pull Requests Close Count51
项目设置
Has Wiki Enabled
Is Archived
Is Fork
Is Locked
Is Mirror
Is Private