diff options
author | eug-vs <eug-vs@keemail.me> | 2020-11-14 16:31:59 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2020-11-14 16:31:59 +0300 |
commit | 36465387454cdb797f886f732d40a70faa92cbad (patch) | |
tree | 28616bd04e3e98c5bd40e82b0c674a0ea9437357 /src/connectDb.js | |
parent | 2a791b8999dc08824baf6787021d45df676b4088 (diff) | |
download | bsu-fantom-36465387454cdb797f886f732d40a70faa92cbad.tar.gz |
refactor: reuse Mongoose connection in Agenda
Diffstat (limited to 'src/connectDb.js')
-rw-r--r-- | src/connectDb.js | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/connectDb.js b/src/connectDb.js new file mode 100644 index 0000000..c7ad13b --- /dev/null +++ b/src/connectDb.js @@ -0,0 +1,40 @@ +const mongoose = require('mongoose'); +const Promise = require('bluebird'); + +const MONGODB_URL = process.env.MONGODB_URI || 'mongodb://localhost:27017/bsu-fantom'; +const { MONGODB_USER, MONGODB_PASSWORD } = process.env; + +let connection; + +const connectDb = () => new Promise ((resolve, reject) => { + mongoose.Promise = Promise; + + mongoose.connect(MONGODB_URL, { + user: MONGODB_USER, + pass: MONGODB_PASSWORD, + useNewUrlParser: true, + useUnifiedTopology: true, + useCreateIndex: true, + useFindAndModify: false, + family: 4 // Use IPv4, skip trying IPv6 + }); + + connection = mongoose.connection; + + connection.on('error', error => { + console.log(error); + reject(error); + }); + + connection.once('open', () => { + console.log('Connection to MongoDB successfull') + resolve(); + }); +}); + +const getConnection = () => connection; + +module.exports = { + connectDb, + getConnection +}; |