node package manager
Easy collaboration. Discover, share, and reuse code in your team. Create a free org »

mongoose-model-decorators

mongoose-model-decorators

ES2016 decorator functions for building Mongoose models.

As of Mongoose 4.7.0, Mongoose includes a loadClass function with which ES classes can be used to define Mongoose models. It's a bit different than this module, but it may suit your needs. See the docs for more.

Installation - Usage - API - Translations - Licence

Installation

npm install --save mongoose-model-decorators

Currently, there is no official Babel transformer for decorators. To use the @Model decorator syntax, you need to add the decorators-legacy transformer to your .babelrc or other Babel configuration.

npm install --save-dev babel-plugin-transform-decorators-legacy

Usage

import mongoose from 'mongoose'
import { Model } from 'mongoose-model-decorators'
 
@Model
class Channel {
  static schema = {
    channelName: { type: String, index: true },
    channelTopic: String,
    users: Array,
    favorited: { type: Boolean, default: false }
  }
 
  get summary () {
    const users = this.users.length
    return `${this.channelName} : ${this.channelTopic} (${users} active)`
  }
}
 
Channel.findOne({ channelName: '#mongoose' }).then(channel =>
  console.log(channel.summary)
  // → "#mongoose: Now with class syntax! (7 active)" 
})

API

@Schema, @Schema()

Creates a Mongoose Schema from a Class definition.

Define your schema in a static schema property. The contents of that property will be passed to the Mongoose Schema constructor.

@Schema
class User {
  static schema = {
    name: String,
    age: Number,
    email: { type: String, required: true }
  }
}

You can also define a configureSchema method which will be called on the schema after it is instantiated, so you can do anything to it that may not be supported by mongoose-model-decorators otherwise:

@Schema
class User {
  static configureSchema (schema) {
    schema.query.byName = function (name) {
      return this.find({ username: name })
    }
    schema.index({ username: 1, joinedAt: 1 }, { unique: true })
  }
}

@Schema(options={})

Creates a Mongoose Schema from a Class definition.

The possible options are passed straight to the Mongoose Schema constructor.

Options defined in the options object take precedence over options that were defined as static properties on the Schema class. Thus:

@Schema({ collection: 'vip_users' })
class User {
  static autoIndex = false
  static collection = 'users'
}

…results in { autoIndex: false, collection: 'vip_users' } being passed to Mongoose.

@Model, @Model(), @Model(options={})

Creates a Mongoose schema from a class definition, and defines it on the global mongoose connection.

You can specify the Mongoose connection to attach the model to in the connection option (defaults to mongoose). Other options are passed straight through to @Schema.

@Model({ connection: myConnection, collection: 'best_users' })
class User {
  // … 
}

is equivalent to:

@Schema({ collection: 'best_users' })
class UserSchema {
  // … 
}
myConnection.model('User', new UserSchema)

And without a connection option:

@Model
class User { /* … */ }

is equivalent to:

@Schema
class UserSchema { /* … */ }
require('mongoose').model('User', new UserSchema)

createSchema(Class), createSchema(options={})(Class)

Alias to @Schema. This one reads a bit nicer if you're not using decorators:

const UserSchema = createSchema(UserClass)

createModel(Class), createModel(options={})(Class)

Alias to @Model. Reads a bit nicer if you're not using decorators:

const UserModel = createModel({ collection: 'best_users' })(UserClass)

Usage without decorators support

If your project configuration doesn't support decorators, you can still use most mongoose-model-decorators translations. Instead of using the @Decorator syntax, you can call the decorator as a function, passing the class definition:

import { createSchema, createModel } from 'mongoose-model-decorators'
class UserTemplate {
  static schema = {
    // ... 
  }
 
  getFriends() {
    // ... 
  }
}
// then use any of: 
const UserSchema = createSchema(UserTemplate)
const UserSchema = createSchema()(UserTemplate)
const UserSchema = createSchema(options)(UserTemplate)
// or even: 
const UserSchema = createSchema(class {
  // ... 
})
// or for models: 
const User = createModel(UserTemplate)
const User = createModel()(UserTemplate)
const User = createModel(options)(UserTemplate)
// or even: 
createModel(class User {
  // ... 
})

Translations

mongoose-model-decorators translates as many ES2015 class things to their Mongoose Schema and Model equivalents as possible, as transparently as possible.

Feature mongoose-model-decorators plain Mongoose
Instance methods
methodName () {
  console.log('hi!')
}
schema.method('methodName', function methodName () {
  console.log('hi!')
})
Instance getters
get propName () {
  return 10
}
schema.virtual('propName').get(function () {
  return 10
})
Instance setters
set propName (val) {
  console.log('set', val)
}
schema.virtual('propName').set(function (val) {
  console.log('set', val)
})
Pre/post hooks
@pre('validate')
makeSlug () {
  this.slug = slugify(this.username)
}
schema.pre('validate', function makeSlug () {
  this.slug = slugify(this.username)
})
Static methods
static methodName () {
  console.log('static!')
}
schema.static('methodName', function methodName () {
  console.log('static!')
})
Static properties
static prop = 'SOME_CONSTANT'
schema.on('init', function (ModelClass) {
  Object.defineProperty(ModelClass, 'prop', {
    value: 'SOME_CONSTANT'
  })
})
Static properties are a bit hacky, because Mongoose doesn't have a shorthand for them (only for static methods). They work well though :)
NB: static properties that are also Schema options are also copied.
Static getters and setters
static get propName () {
  return 20
}
static set propName () {
  throw new Error('Don\'t set this :(')
}
schema.on('init', function (ModelClass) {
  Object.defineProperty(ModelClass, 'propName', {
    get: function () {
      return 20
    },
    set: function () {
      throw new Error('Don\'t set this :(')
    }
  })
})

Licence

MIT