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. const modb = require('mongoose'),
  3. fs = require("fs"),
  4. path = require("path"),
  5. _ = require('lodash');
  6. /**
  7. * MongoDB module
  8. *
  9. * @param {Object} appconfig Application config
  10. * @return {Object} MongoDB wrapper instance
  11. */
  12. module.exports = {
  13. /**
  14. * Initialize DB
  15. *
  16. * @param {Object} appconfig The application config
  17. * @return {Object} DB instance
  18. */
  19. init(appconfig) {
  20. let self = this;
  21. let dbModelsPath = path.resolve(ROOTPATH, 'models');
  22. modb.Promise = require('bluebird');
  23. // Event handlers
  24. modb.connection.on('error', (err) => {
  25. winston.error('[' + PROCNAME + '] Failed to connect to MongoDB instance.');
  26. });
  27. modb.connection.once('open', function() {
  28. winston.log('[' + PROCNAME + '] 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);
  45. return self;
  46. }
  47. };