You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.4 KiB

  1. 'use strict'
  2. /* global ROOTPATH, appconfig, winston */
  3. const modb = require('mongoose')
  4. const fs = require('fs')
  5. const path = require('path')
  6. const _ = require('lodash')
  7. /**
  8. * MongoDB module
  9. *
  10. * @return {Object} MongoDB wrapper instance
  11. */
  12. module.exports = {
  13. /**
  14. * Initialize DB
  15. *
  16. * @return {Object} DB instance
  17. */
  18. init () {
  19. let self = this
  20. global.Mongoose = modb
  21. let dbModelsPath = path.resolve(ROOTPATH, 'models')
  22. modb.Promise = require('bluebird')
  23. // Event handlers
  24. modb.connection.on('error', err => {
  25. winston.error('Failed to connect to MongoDB instance.')
  26. return err
  27. })
  28. modb.connection.once('open', function () {
  29. winston.log('Connected to MongoDB instance.')
  30. })
  31. // Store connection handle
  32. self.connection = modb.connection
  33. self.ObjectId = modb.Types.ObjectId
  34. // Load DB Models
  35. fs
  36. .readdirSync(dbModelsPath)
  37. .filter(function (file) {
  38. return (file.indexOf('.') !== 0)
  39. })
  40. .forEach(function (file) {
  41. let modelName = _.upperFirst(_.camelCase(_.split(file, '.')[0]))
  42. self[modelName] = require(path.join(dbModelsPath, file))
  43. })
  44. // Using ENV variable?
  45. if (_.startsWith(appconfig.db, '$')) {
  46. appconfig.db = process.env[appconfig.db.slice(1)]
  47. }
  48. // Connect
  49. self.onReady = modb.connect(appconfig.db)
  50. return self
  51. }
  52. }