|
1 | 1 | /* eslint-disable no-param-reassign, no-console */ |
2 | 2 | import mongoose, { Schema } from 'mongoose'; |
3 | | - |
4 | | -function getRandomInt(min, max) { |
5 | | - return Math.floor(Math.random() * (max - min)) + min; |
6 | | -} |
7 | | - |
8 | | -const dbName = `gqc-mongoose-test${getRandomInt(1, 1000000)}`; |
9 | | -const uri = `mongodb://127.0.0.1:27017/${dbName}`; |
| 3 | +import MongodbMemoryServer from 'mongodb-memory-server'; |
10 | 4 |
|
11 | 5 | mongoose.Promise = Promise; |
12 | | -mongoose.connect(uri); |
13 | 6 |
|
14 | | -mongoose.connection.on('error', (err) => { |
15 | | - throw new Error(err); |
16 | | -}); |
| 7 | +const mongoServer = new MongodbMemoryServer(); |
17 | 8 |
|
18 | | -mongoose.connection.on('connected', () => { |
19 | | - console.log(`Mongoose default connection open to ${uri}`); |
20 | | -}); |
| 9 | +mongoServer.getConnectionString().then((mongoUri) => { |
| 10 | + mongoose.connect(mongoUri); |
21 | 11 |
|
22 | | -function dropDBs(done) { |
23 | | - try { |
24 | | - mongoose.connection.db.dropDatabase(() => { |
25 | | - if (done) done(); |
26 | | - }); |
27 | | - } catch (e) { // Pitty, but not deathly |
28 | | - if (done) done(); |
29 | | - } |
30 | | -} |
| 12 | + mongoose.connection.on('error', (e) => { |
| 13 | + if (e.message.code === 'ETIMEDOUT') { |
| 14 | + console.log(e); |
| 15 | + mongoose.connect(mongoUri); |
| 16 | + } else { |
| 17 | + throw e; |
| 18 | + } |
| 19 | + }); |
31 | 20 |
|
32 | | -process.on('exit', () => { dropDBs(); }); |
33 | | -process.on('SIGINT', () => { dropDBs(); }); |
| 21 | + mongoose.connection.once('open', () => { |
| 22 | + console.log(`MongoDB successfully connected to ${mongoUri}`); |
| 23 | + }); |
| 24 | +}); |
34 | 25 |
|
35 | 26 | export { |
36 | 27 | mongoose, |
37 | 28 | Schema, |
38 | | - dropDBs, |
39 | | - uri, |
40 | | - dbName, |
41 | 29 | }; |
0 commit comments