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.

52 lines
1.1 KiB

  1. "use strict";
  2. var 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} Mongoose instance
  11. */
  12. module.exports = function(appconfig) {
  13. modb.Promise = require('bluebird');
  14. let dbModels = {};
  15. let dbModelsPath = path.join(ROOTPATH, 'models/db');
  16. // Event handlers
  17. modb.connection.on('error', (err) => {
  18. winston.error('Failed to connect to MongoDB instance.');
  19. });
  20. modb.connection.once('open', function() {
  21. winston.log('Connected to MongoDB instance.');
  22. });
  23. // Store connection handle
  24. dbModels.connection = modb.connection;
  25. dbModels.ObjectId = modb.Types.ObjectId;
  26. // Load Models
  27. fs
  28. .readdirSync(dbModelsPath)
  29. .filter(function(file) {
  30. return (file.indexOf(".") !== 0);
  31. })
  32. .forEach(function(file) {
  33. let modelName = _.upperFirst(_.split(file,'.')[0]);
  34. dbModels[modelName] = require(path.join(dbModelsPath, file));
  35. });
  36. // Connect
  37. dbModels.connectPromise = modb.connect(appconfig.db);
  38. return dbModels;
  39. };