-
-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathmongooseCommon.ts
More file actions
42 lines (32 loc) · 1.11 KB
/
mongooseCommon.ts
File metadata and controls
42 lines (32 loc) · 1.11 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
/* eslint-disable no-param-reassign, no-console */
import mongoose from 'mongoose';
import MongoMemoryServer from 'mongodb-memory-server-core';
const { Schema, Types } = mongoose;
mongoose.Promise = Promise;
const originalConnect = mongoose.connect;
mongoose.createConnection = (async () => {
const mongoServer = await MongoMemoryServer.create();
const mongoUri = await mongoServer.getUri();
// originalConnect.bind(mongoose)(mongoUri, { useMongoClient: true }); // mongoose 4
originalConnect.bind(mongoose)(mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}); // mongoose 5
mongoose.connection.on('error', (e) => {
if (e.message.code === 'ETIMEDOUT') {
console.error(e);
} else {
throw e;
}
});
mongoose.connection.once('open', () => {
// console.log(`MongoDB successfully connected to ${mongoUri}`);
});
mongoose.connection.once('disconnected', () => {
// console.log('MongoDB disconnected!');
mongoServer.stop();
});
}) as any;
mongoose.connect = mongoose.createConnection as any;
export { mongoose, Schema, Types };