typeodm.io
Improve typescript experience using mongoose with decorators.
Features
typescript
first class support.- Build your entire documents with decorators.
- Fully tested (unit and integration test for every line of code).
- Easy to use.
- Nothing new to learn (It's just mongoose in a decorator way)
Installation
npm install typeodm.io --save
Requirements
Dependencies
npm install metadata mongoose @types/mongoose --save
Remember enable decorators in tsconfig.json
"experimentalDecorators": true,
"emitDecoratorMetadata": true
Getting Started
defining simple 'User' document and export model
/* user.document.ts */ ;
using UserModel
/* Somewhere in your code, basic CRUD operations */ // Get ListUserModel.find; // Get oneUserModel.findOne;UserModel.findByIdid; // Save;user.save; // UpdateUserModel.findByIdAndUpdateid, ; // RemoveUserModel.findByIdAndRemoveid;
You can find more useful functions for 'UserModel' here
Core:
Schema Types:
All Schema Types
-
@objectId
-
@required
-
@optional
-
@defaultValue
(alias fordefault
) -
@validate
-
@alias
Indexes
-
@unique
-
@index
-
@spare
String
-
@lowercase
-
@uppercase
-
@trim
-
@match
-
@isIn
(alias forenum
) -
@length
(includesminlength
andmaxlength
ex.@length(3, 50)
)
Number
-
@range
(includesmin
andmax
)
Date
-
@range
(includesmin
andmax
)
Schema
-
@methods
-
@virtuals
-
@query
(Not have type support yet, but works fine) -
@statics
(Not have type support yet, but works fine)
Use case Post-Comment
A comment only exists and belong to one post, therefore it must be saved as a subdocument, hasn't sense to create a collection to store comments. Example:
Use case User-Todo
In almost all applications the resource are store by user, in this case we'll see how to create documents 'User' and 'Todo' where each 'Todo' belong to a user.
;
Getting a Todo
list with the user data populated.
Using populate query
to property 'Todo.user' and projection username
to return only User._id
and User.username
;
Now will see how to save a Todo
// getting user by creating a new one;; // getting user by data base query; // getting user from request after jwt put it there; // after getting the `user._id` no matter what source you can save a `Todo` for this user in the following way:;todoToSave.user = user._id;; // in some case you don't now if user._id if an instance of ObjectId, to be sure do:;
API
@document
You must annotate a class with @document
in order to use is as mongoose schema and to can extract a model from it.
@document(config: SchemaOptions)
you can pass a SchemaOptions object as parameter.
Todo:
- find a way to set correct types for
@query
and@statics
- add
@plugin
decorator - improve api doc
- improve use-case examples