0.1.4 • Published 6 years ago

@sagnol/decorator-mongoose-model v0.1.4

Weekly downloads
1
License
ISC
Repository
github
Last release
6 years ago

decorator-mongoose-model

CircleCI

Inspired by Typegoose, inversify-express-utils module.
Caution! This is personal project.
(lack of API, not fully tested, unstable api)

Installation

You can install @sagnol/decorator-mongoose-model using npm;

npm install --save @sagnol/decorator-mongoose-model reflect-metadata

The Basics

Step 1: Decorate your models

import { Document, Prop } from "decorator-mongoose-model";

@Document("mySchema")
class MySchema {
    @Prop()
    name: string;

    @Prop({
        required: true,
        default: 'my@email.com'
    })
    email: string;
}

Step 2: Statice, Instance methods

you don't need to (@staticMethod, @instanceMethod) any decoration. reference http://mongoosejs.com/docs/advanced_schemas.html

import { Document, Prop } from "decorator-mongoose-model";

@Document("mySchema")
class MySchema {
    @Prop()
    name: string;

    @Prop({
        required: true,
        default: 'my@email.com'
    })
    email: string;

    static isTestify():boolean {
        return true;
    }

    getEmail():string {
        return this.email;
    }
}

instance method can access types, But, static method cannot access types. need to interface.

Step 3: Connection & Build model

import mongoose from "mongoose";
import { ModelBuilder, Interfaces, ModelType } from "decorator-mongoose-model";

const connection = mongoose.createConnection("mongodb://localhost:27017");

export interface DB extends Interfaces.MongoModels {
    MySchema: ModelType<MySchema>
}

const models = ModelBuilder.initiate({ connection }) as DB;

Schema options

Refer to mongoose schema options http://mongoosejs.com/docs/guide.html#options

@Document("mySchema", {
    autoIndex: true,
    strict: true,
    timestamps: {
        createdAt: 'created_at', 
        updatedAt: 'updated_at'
    }
})
class MySchema {
    @Prop()
    name: string;

    @Prop({
        required: true,
        default: 'my@email.com'
    })
    email: string;
}

Todo

  1. staticMethod interface
  2. relation
  3. Hook, Pre, Post decorator