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.

63 lines
1.3 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. let dbModelsPath = path.join(SERVERPATH, 'models')
  21. modb.Promise = require('bluebird')
  22. // Event handlers
  23. modb.connection.on('error', err => {
  24. winston.error('Failed to connect to MongoDB instance.')
  25. return err
  26. })
  27. modb.connection.once('open', function () {
  28. winston.log('Connected to MongoDB instance.')
  29. })
  30. // Store connection handle
  31. self.connection = modb.connection
  32. self.ObjectId = modb.Types.ObjectId
  33. // Load DB Models
  34. fs
  35. .readdirSync(dbModelsPath)
  36. .filter(function (file) {
  37. return (file.indexOf('.') !== 0)
  38. })
  39. .forEach(function (file) {
  40. let modelName = _.upperFirst(_.camelCase(_.split(file, '.')[0]))
  41. self[modelName] = require(path.join(dbModelsPath, file))
  42. })
  43. // Connect
  44. self.onReady = modb.connect(appconfig.db, { useMongoClient: true })
  45. return self
  46. }
  47. }