This repository was archived by the owner on Feb 23, 2021. It is now read-only.
forked from samloh84/node-example-express-app
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmongooseService.js
57 lines (41 loc) · 1.75 KB
/
mongooseService.js
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
26
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
const _ = require('lodash');
const Promise = require('bluebird');
const mongoose = require('mongoose');
const models = require('../models');
const config = require('../config/index');
const loggingService = require('./loggingService');
const MONGODB_HOST = config.env('MONGODB_HOST', config.get('mongodb.host', 'localhost'));
const MONGODB_PORT = config.env('MONGODB_PORT', config.get('mongodb.port', 27017));
const MONGODB_USERNAME = config.env('MONGODB_USERNAME', config.get('mongodb.username'));
const MONGODB_PASSWORD = config.env('MONGODB_PASSWORD', config.get('mongodb.password'));
const MONGODB_DATABASE = config.env('MONGODB_DATABASE', config.get('mongodb.database'));
mongoose.Promise = Promise;
const mongooseService = {
mongoose: mongoose
};
_.forIn(models, function (schema, name) {
mongoose.model(name, schema);
});
mongooseService.connect = function () {
let mongodbUrl = `mongodb://`;
if (!_.isNil(MONGODB_USERNAME) && !_.isNil(MONGODB_PASSWORD)) {
mongodbUrl += `${MONGODB_USERNAME}:${MONGODB_PASSWORD}@`;
}
mongodbUrl += `${MONGODB_HOST}:${MONGODB_PORT}`;
if (!_.isNil(MONGODB_DATABASE)) {
mongodbUrl += `/${MONGODB_DATABASE}`;
}
return mongoose.connect(mongodbUrl, {useNewUrlParser: true})
.tap(function () {
let mongodbUrl = `mongodb://`;
if (!_.isNil(MONGODB_USERNAME) && !_.isNil(MONGODB_PASSWORD)) {
mongodbUrl += `${MONGODB_USERNAME}@`;
}
mongodbUrl += `${MONGODB_HOST}:${MONGODB_PORT}`;
if (!_.isNil(MONGODB_DATABASE)) {
mongodbUrl += `/${MONGODB_DATABASE}`;
}
loggingService.info(`Connected to MongoDB server:\n` + mongodbUrl)
});
};
module.exports = mongooseService;