mongoose-simple-decorator v2.0.1
Mongoose Simple Decorator
With mongoose, you have to define a schema
and model
. In addition, if you want to use a type for a Typescript project you also have to define a type
. Therefore, if you change something in the type
you must change it in the schema
. The solution, have the type
and the schema
together
Problem
import * as mongoose from 'mongoose'
import { Schema, Document } from 'mongoose'
/**
* Definition of the BasicType
*/
type UserType = {
...
}
/**
* Schema
*/
const UserSchema = new Schema({
...
})
/**
* Model
*/
var IdModel = mongoose.model('User', UserSchema)
Solution
import { Schema, Field } from 'mongoose-simple-decorator'
@Schema()
class User {
_id: string
@Field({ type: String, required: true })
username: string
}
Install
yarn add mongoose-simple-decorator
npm i mongoose-simple-decorator
Usage
Class Definition
Declare a class
with the Schema
decorator. It's going to add the schema
and the model
using Reflect
library. Define id
property, it's the ObjectId
string representation.
@Schema()
class User {
public id: string
}
Properties or Fields
Declare the properties
with the Field
decorator. It's going to add properties to the schema
. The type
of the Field's params
are the same as the schema properties
.
@Schema()
class User {
_id: string
@Field({ type: String, required: true })
username: string
}
Middleware
Declare the middlewares
as private
, static
, property
. private
to make it invisible to the rest of the application, static
to make it accesible to the Schema
decorator and property to assign the Middleware Function Type
@Schema()
class User {
_id: string
@Field({ type: String, required: true })
username: string
@Field({ type: String, required: true })
password: string
@PreHook('save')
private static encryptPassword: FuncMongooseMiddleware.DocumentRef<User> = (_this, next) => {
...
}
}
Saving the Document
const user = new User()
// do stuff ...
const userDoc = Document(user)
userDoc.save()
The Final Document
// DATABASE.users
{
"_id":"5b00c2898e5f9f3010d90614",
"username":"Arthaclarius",
"password":"ThisIsAVeryLongPassword",
"age":20,
"__v":0
}
Overview
// --- User.ts
@Schema()
class User {
_id: string
@Field({ type: String, required: true })
username: string
@Field({ type: String, required: true })
password: string
@PreHook('save')
private static encryptPassword: FuncMongooseMiddleware.DocumentRef<User> = (_this, next) => {
_this.password = `encrypt(${_this.password})`
}
}
// --- Another_Place.ts
// Find
Model(User).find('5b00c2898e5f9f3010d90614')
// Save
const user = new User()
user.username = 'CoolUniqueUserName'
user.password = 'SecurePassword'
Document(user).save()