Typegoose
(These badges are from typegoose:master)
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;
}
const UserModel = getModelForClass(User);
(async () => {
await mongoose.connect('mongodb://localhost:27017/', { useNewUrlParser: true, useUnifiedTopology: true, dbName: "test" });
const { _id: id } = await UserModel.create({ name: 'JohnDoe' } as User);
const user = await UserModel.findById(id).exec();
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 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:
interface Car {
model?: string;
}
interface Job {
title?: string;
position?: string;
}
interface User {
name?: string;
age: number;
job?: Job;
car: Car | string;
}
mongoose.model('User', {
name: String,
age: { type: Number, required: true },
job: {
title: String;
position: String;
},
car: { type: Schema.Types.ObjectId, ref: 'Car' }
});
mongoose.model('Car', {
model: string,
});
You can just:
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>;
}
Extra Examples
Requirements
- TypeScript 3.9+
- Node 10.15+
- mongoose ^5.9.22
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
npm i -s mongoose
npm i -D @types/mongoose
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.