Mongoose Connection Initializer
JS
S
JavaScriptBasic mongoose connection initializer
1 public initializeDbConnection(): void {
2
3 // Atomic DB Connection
4 const connectionOpts = {
5 useNewUrlParser: true,
6 server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
7 replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
8 };
9 (<any>mongoose).Promise = bluebird;
10 this.db = mongoose.connection;
11 this.db.once('open', () => {
12 logService.log('debug', 'Database connection is open.');
13 });
14 this.db.on('error', (err) => {
15 logService.log('debug', 'Database connection error.', err);
16 if (err) throw err;
17 process.exit(1);
18 });
19 mongoose.connect(process.env.MONGODB_URI, connectionOpts)
20 .then(
21 () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
22 ).catch(err => {
23 logService.log(`error`, `MongoDB connection error. Please make sure MongoDB is running`, err);
24 process.exit(1);
25 });
26 }Created on 3/7/2019