Code Monkey home page Code Monkey logo

spool-mongoose's Introduction

spool-mongoose

๐Ÿ“ฆ Mongoose.js Spool http://mongoosejs.com

Gitter NPM version Build Status Test Coverage Dependency Status Follow @FabrixApp on Twitter

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

Usage

Include spool in app.

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

Configure stores.

// config/stores.ts
export const stores = {

  /**
   * 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
   */
  someteststore: {
    // migration
    migrate: 'create',
    // Mongodb URI
    uri: 'mongodb://localhost:27017/test',
    // Mongoose connection options
    options: {

    },
    // Set this stores orm to mongoose
    orm: 'mongoose'
  }
}

// config/models.ts
export const models = {
  defaultStore: 'someteststore',
  migrate: 'drop'
}

Models

Options

Model::Schema

See Mongoose Documentation for Schemas.

Model::Config
Option Type Default Description
tableName String modelName.toLowerCase() Name of collection to use with this model. For example: MyModel.js defaults to collection named mymodel
store String app.config.database.models.defaultStore Datastore to use for this model; specify the name of one of the stores in app.config.database.stores.
migrate String Migrate must be set to one of [ 'none', 'drop', 'create' ]
schema Object {} Schema Options to pass into Mongoose's Schema constructor.
statics Object {} Static methods to add to the Model.
methods Object {} Instance methods to add to this model's documents.
onSchema Function undefined Funcion which is useful to for adding schema middleware, virtuals, or indexes.

Example

// 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 Fabrix.js will create model Schema you could add anything you want here
        * @param  {FabrixApp} app FabrixJs app object
        * @param  {mongoose.Schema} schema mongoose new Schema object
      */
      onSchema (app, 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()
          })
          
          // text indexes
          schema.index(
            { 
              username: 'text',
              email: 'text'
            },
            { 
              weights : {
                username : 10,
                email: 5
              },
              name: "usersIndex"
            }
          )
        }
    }
  }
}

Query

// 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

Changelog

Changelog

spool-mongoose's People

Contributors

scott-wyatt avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.