Skip to content

LobeTia/trailpack-mongoose

 
 

Repository files navigation

trailpack-mongoose

📦 Mongoose.js Trailpack http://mongoosejs.com

Gitter NPM version Build status Dependency Status Code Climate

Loads Application Models (in api/models) into the Mongoose ORM; Integrates with trailpack-router to generate Footprints for routes.

Usage

Configure

// config/main.js
module.exports = {
  // ...
  packs: [
    require('trailpack-mongoose')
  ]
}

Configure stores

// config/database.js
module.exports = {

  /**
   * Define the database stores. A store is typically a single database.
   *
   * Use the SQLite3 by default for development purposes.
   *
   * Set production connection info in config/env/production.js
   */
  stores: {

    /**
     * Define a store called "local" which uses SQLite3 to persist data.
     */
    someteststore: {
      //migration
      migrate: 'create',
      // Mongodb URI
      uri: 'mongodb://localhost:27017/test',
      // Mongoose connection options
      options: {

      }
    }
  },

  models: {
    defaultStore: 'someteststore',
    migrate: 'drop'
  }
}

Models

// Use default Schema from Mongoose. See http://mongoosejs.com/docs/schematypes.html
module.exports = class User extends Model {

  static schema (app, Mongoose) {
    return {
      username: String,
      childs: [{
        type: Mongoose.Schema.ObjectId,
        ref: 'UserSchema'
      }],
      email: {
        type: String,
        required: true,
        unique: true,
        lowercase: true,
        trim: true,
        validate: {
          validator: function (val) {
            return isEmail(val)
          },
          message: '{VALUE} is not a valid email'
        }
      }
    }
  }

  static config (app, Mongoose) {
    return {
      // Collection name
      tableName: 'users',

      // Schema options
      schema: {
        timestamps: true,

        versionKey: false,

        toObject: {
          virtuals: true
        },

        toJSON: {
          virtuals: true
        }
      },
      // Schema statics
      statics: {
        getByEmail: function (email) {
          return this
            .findOne({
              email: _.trim(email)
            })
            .exec()
        },
      },

      // Schema methods
      methods: {
        toJSON: function () {
          const user = this.toObject()
          delete user.password

          return user
        }
      }
    }
  }
  /**
   * After Trails.js will create model Schema you could add anything you want here
   * @param  {mongoose.Schema} schema mongoose new Schema object
   */
  static onSchema (schema) {
    // virtuals
    schema.virtual('name.full').get(function () {
      return this.name.first + ' ' + this.name.last
    })
    // lifecircle events
    schema.pre('save', function (next) {
      // performing actions
      next()
    })
  }
}```

### Query

```js
// api/services/UserService.js
module.exports = class UserService extends Service {
  /**
   * Finds people with the given email.
   * @return Promise
   * @example {
   *    name: 'Ludwig Beethoven',
   *    email: '[email protected]',
   *    favoriteColors: [
   *      { name: 'yellow', hex: 'ffff00' },
   *      { name: 'black', hex: '000000' }
   *     ]
   * }
   */
  findUser (email) {
    return this.orm.User.find({ email: email })
      .exec()
  }
}

Contributing

We love contributions! Please check out our Contributor's Guide for more information on how our projects are organized and how to get started.

License

MIT

Packages

No packages published

Languages

  • JavaScript 100.0%