Skip to content
Set of decorators to define mongoose model with es6 class
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
test
.gitignore
CHANGELOG.md
LICENSE
README.md
jest.config.js
package.json
tsconfig.json
tslint.json
yarn.lock

README.md

Mongoose Model Decorator

Set of decorators to define mongoose model with es6 class

Installation

yarn add -D mongoose-model-decorator
# or
npm i mongoose-model-decorator --save-dev

Usage

  • Create a model
/**
 * Post.ts
 **/
import { Model, Schema } from 'mongoose'
import { field, doc, pre, post, method } from 'mongoose-model-decorator';

@doc()
export default class Post extends Model {
    @field(Schema.Types.String)
    title?: String

    @field(Schema.Types.String)
    page?: String
    
    @field({ type: Schema.Types.String })
    raw_content?: String

    @field([Schema.Types.String])
    hooks: String[] = []

    @pre('save')
    preLog() {
        this.hooks.push('pre save')
    }

    @post('save')
    postLlog() {
        this.hooks.push('post save')
    }

    /**
     * Define instance methods
     * @param prefix 
     */
    @method()
    prefixedTitle(prefix: string) {
        return prefix + this.title
    }

    /**
     * Define static methods
     * @param title 
     * @param cb 
     */
    static findByTitle(title: string, cb?: any): any {
        return this.find({ title: new RegExp(title, 'i') }, cb);
    }
}
  • And use it
import mongoose from 'mongoose'
import Post from './Post'

await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true })

Post.findByTitle('title')
    .then(posts => posts.map(post => post.prefixedTitle('prefix--')))
    .then(titles => console.log(titles))
  • If you receive error while using decorators, add "experimentalDecorators": true in compilerOptions of your tsconfig.json

Inspired of

You can’t perform that action at this time.