|
require('dotenv').config(); |
|
const mongoose = require('mongoose'); |
|
const MONGO_URI = process.env.MONGO_URI; |
|
|
|
if (!MONGO_URI) { |
|
throw new Error('Please define the MONGO_URI environment variable'); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
let cached = global.mongoose; |
|
|
|
if (!cached) { |
|
cached = global.mongoose = { conn: null, promise: null }; |
|
} |
|
|
|
async function connectDb() { |
|
if (cached.conn) { |
|
return cached.conn; |
|
} |
|
|
|
if (!cached.promise) { |
|
const opts = { |
|
useNewUrlParser: true, |
|
useUnifiedTopology: true, |
|
bufferCommands: false, |
|
|
|
|
|
|
|
}; |
|
|
|
mongoose.set('strictQuery', true); |
|
cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => { |
|
return mongoose; |
|
}); |
|
} |
|
cached.conn = await cached.promise; |
|
return cached.conn; |
|
} |
|
|
|
module.exports = connectDb; |
|
|