db.js 1.24 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
'use strict'

/* global ROOTPATH, appconfig, winston */

const modb = require('mongoose')
const fs = require('fs')
const path = require('path')
const _ = require('lodash')

/**
 * MongoDB module
 *
 * @return     {Object}  MongoDB wrapper instance
 */
module.exports = {

  /**
   * Initialize DB
   *
   * @return     {Object}  DB instance
   */
  init () {
    let self = this
    global.Mongoose = modb

26
    let dbModelsPath = path.join(SERVERPATH, 'models')
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

    modb.Promise = require('bluebird')

    // Event handlers

    modb.connection.on('error', err => {
      winston.error('Failed to connect to MongoDB instance.')
      return err
    })
    modb.connection.once('open', function () {
      winston.log('Connected to MongoDB instance.')
    })

    // Store connection handle

    self.connection = modb.connection
    self.ObjectId = modb.Types.ObjectId

    // Load DB Models

    fs
    .readdirSync(dbModelsPath)
    .filter(function (file) {
      return (file.indexOf('.') !== 0)
    })
    .forEach(function (file) {
      let modelName = _.upperFirst(_.camelCase(_.split(file, '.')[0]))
      self[modelName] = require(path.join(dbModelsPath, file))
    })

    // Connect

    self.onReady = modb.connect(appconfig.db)

    return self
  }

}