mongoose-helpers-connection

0.1.4 • Public • Published

mongoose-helpers-connection

NPM version Build Status NSP Status

returns a mongoose connection promise.

note: you can use mongoose-helpers-setup-db instead of using this module directly.

table of contents

notes

logging

  • error events will be logged to the console
  • additional logging - if options.connection.debug is set to true the following events will also be logged to the console
    • connected
    • connecting
    • disconnected
    • open
    • reconnected

errors

  • if an error occurs, the error will be attached to the db object as db.error.

installation

npm install mongoose-helpers-connection

usage

var express = require( 'express' )
var connection = require( 'mongoose-helpers-connection' )
var mongoose = require( 'mongoose' )
var app = express()
 
var User = new mongoose.Schema(
  {
    displayName: String,
    email: String,
    id: String,
    photo: String
  }
)
 
var options = {
  connection: {
    debug: config.debug,
    uri: {
      database: config.database,
      password: config.password,
      username: config.username
    }
  },
  schemas: [
    {
      'User': User
    }
  ]
}
 
function setupDb( options ) {
  return connection( options.connection )
   .then(
     function ( db ) {
       try {
         if ( Array.isArray( options.schemas ) ) {
           options.schemas.forEach(
             function ( schema ) {
               var keys = Object.keys( schema )
 
               db.model( keys[ 0 ], schema[ keys[ 0 ] ] )
             }
           );
         }
 
         return db;
       } catch ( err ) {
         throw err
       }
     }
   )
   .catch(
     function ( err ) {
       throw err
     }
   )
}
 
setupDb( options )
  .then(
    function ( db ) {
      app.db = db
    }
  )
  .catch(
    function ( err ) {
      app.db = {
        error: err
      }
    }
  )
 
// elsewhere in your app
app.db.model( 'User' )
  .findOne(
    { 'id': id },
    function( err, existing_user ) {}
  )

license

MIT License

Package Sidebar

Install

npm i mongoose-helpers-connection

Weekly Downloads

3

Version

0.1.4

License

MIT

Unpacked Size

29 kB

Total Files

17

Last publish

Collaborators

  • dentous