Automatically infer TypeScript interfaces from mongoose schemas.
Installation
npm i ts-mongoose mongoose @types/mongoose
yarn add ts-mongoose mongoose @types/mongoose
The Problem
When using mongoose and Typescript, you must define schemas and interfaces. Both definitions must be maintained separately and must match each other. It can be error-prone during development and cause overhead.
ts-mongoose is a very lightweight library that allows you to create a mongoose schema and a typescript type from a common definition.
All types as created from 1-liner functions and does not depend on decorators❗️.
For example: Type.string({ required: true }) returns {type: String, required: true}, which is the same definition required in the original mongoose library.
schema.of(ExampleSchema) has typical for Subdocument additional fields and methods. Setting { _id: false } in SchemaOptions won't attach _id property in Subdocument
constAddressSchema=createSchema(
{city:Type.string({required:true})},
{_id:false,timestamps:true}
);
{
// same as {type: AddressSchema}
address: Type.schema().of(AddressSchema);
}
// address property has city property, other Subdocument methods and properties except '_id'
array.of(ExampleSchema) will return DocumentArray instead of standard array
constPhoneSchema=createSchema(
{phoneNumber:Type.number({required:true})},
{_id:false}
);
{
// same as {type: [PhoneSchema]}
phones: Type.array().of(PhoneSchema);
}
// phones property has such methods as create(), id(), but also those typical for arrays like map(), filter() etc
ref is a special type for creating references
{
// same as [{type: Schema.Types.ObjectId, ref: 'Comment'}]
populateTs(property: string) use this function to populate a property and adjust the returned type automatically. Under the hood it calls only the native populate method.
Method will be available if you import a special plugin.
// models.ts
import'ts-mongoose/plugin';
User.find().populateTs('comments');
Extracting Document type
Use ExtractDoc to extract generated document type.
Use ExtractProps to extract generated base model properties.
Example:
// access all properties + Document methods and properties
awaituser.save();
}
functionrandomUser():UserProps{
// must return `email`, `username`
// `isBlocked` is optional
return{
email:'user1@example.com',
username:'user1',
};
}
Refs
Refs and populations are supported.
Check code under example/example4.ts.
Custom Field
If you need to specify custom fields in the model, you can add a fake annotation.
It's only required if you add virtual fields or custom methods to the model.
constUserSchema=createSchema({
title:Type.string({required:true}),
author:Type.string({required:true}),
...({}as{
generatedField:string;
customFunction:()=>number;
}),
});
constUser=typedModel('User',UserSchema);
Autocomplete popup:
Static methods
If you need to have static custom methods on Model you can pass them as 5th parameter of typedModel function. It should automatically figured out returning value, but you can declare it too.
If you are using mongoose.createConnection(...), you can pass a <mongoose.Connection> as the 6th parameter of typedModel. Then the module will be added to that connection instead.
(Note: If using the connection parameter, the skipInit parameter will not be used)