Mongoose initialiser for Node.js applications

JS
S
JavaScript

Simple initialiser for Mongoose on Node.js applications

1  private safeTermination() {
2    mongoose.disconnect().then(() => {
3      logService.log('MongoDB safely shutting down interface...');
4      process.exit(1);
5    });
6  }
7
8  public initialize(): void {
9    process.once('SIGINT', () => {
10      this.safeTermination();
11    });
12    mongoose.connect(process.env.MONGODB_URI, (err) => {
13      if (err) {
14        throw err;
15      }
16    });
17    this.db = mongoose.connection;
18    this.db.once('open', () => {
19      logService.log('Database started');
20    });
21    mongoose.connection.on('error', (err) => {
22      if (err) {
23        throw err;
24      }
25      logService.error('MongoDB connection error.', err);
26      process.exit();
27    });
28  }

Created on 5/29/2018