-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo.ts
59 lines (49 loc) · 1.42 KB
/
mongo.ts
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
import mongoose, { Model, Document } from 'mongoose';
import Io from './io';
import { MongoOptions } from './types';
export class Mongo {
public mongoose: mongoose.Mongoose;
public options: MongoOptions;
public constructor(io: Io) {
io.config.defaults({
mongo: {
host: 'localhost',
port: 27017,
db: 'cais',
},
});
this.options = io.config.get<MongoOptions>('mongo');
let conn_string = `mongodb://`;
conn_string += `${this.options.host}`;
conn_string += `:`;
conn_string += `${this.options.port}`;
conn_string += `/`;
conn_string += `${this.options.db}`;
this.mongoose = mongoose;
const options: mongoose.ConnectionOptions = {
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true,
useUnifiedTopology: true,
};
if (this.options.user) {
options.user = this.options.user;
}
if (this.options.pass) {
options.pass = this.options.pass;
}
this.mongoose.connect(conn_string, options);
this.mongoose.connection.on('error', (err): void => {
console.error('MongoDB connection error.');
console.error(err);
process.exit(1);
});
}
public model<T extends Document>(name: string, schema: mongoose.Schema): Model<T> {
return this.mongoose.model(name, schema);
}
public disconnect(): Promise<void> {
return this.mongoose.disconnect();
}
}
export default Mongo;