-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
72 lines (58 loc) · 1.86 KB
/
db.js
File metadata and controls
72 lines (58 loc) · 1.86 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* eslint no-console: 'off' */
import mongoose from 'mongoose';
mongoose.Promise = global.Promise;
mongoose.set('toObject', {
virtuals: true,
getters: true,
versionKey: false
});
mongoose.set('toJSON', {
virtuals: true,
getters: true,
versionKey: false,
transform: (document, object, options) => {
delete object._id;
if (options.hide) {
options.hide.split(' ').forEach(prop => delete object[prop]);
}
return object;
}
});
mongoose.plugin(function normalizeMongooseError(schema, options) {
schema.post(['save', 'update'], function(error, doc, next) {
next(error.errors ? Object.values(error.errors)[0] : error);
});
});
mongoose.connection.on('connected', () => console.log('Connected to database'));
mongoose.connection.on('disconnected', () => console.log('Disconnected from database'));
mongoose.connection.on('error', error => () => console.error('Database connection error:', error));
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('Mongoose disconnected through app termination');
process.exit(0);
});
});
export default {
client: null,
connection: mongoose.connection,
getClient() {
if (this.client) return Promise.resolve(this.client);
return new Promise((resolve, reject) => {
this.connection.on('connected', () => {
this.client = this.connection.getClient();
resolve(this.client);
});
this.connection.on('error', reject);
});
},
connect(uri) {
return mongoose.connect(uri, {
autoIndex: false,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
this.client = this.connection.getClient();
});
}
};