2023-02-06 18:25:11 -05:00
|
|
|
require('dotenv').config();
|
2023-02-05 23:05:07 -05:00
|
|
|
const mongoose = require('mongoose');
|
|
|
|
const MONGO_URI = process.env.MONGO_URI;
|
|
|
|
|
|
|
|
if (!MONGO_URI) {
|
|
|
|
throw new Error('Please define the MONGO_URI environment variable inside .env.local');
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Global is used here to maintain a cached connection across hot reloads
|
|
|
|
* in development. This prevents connections growing exponentially
|
|
|
|
* during API Route usage.
|
|
|
|
*/
|
|
|
|
let cached = global.mongoose;
|
|
|
|
|
|
|
|
if (!cached) {
|
|
|
|
cached = global.mongoose = { conn: null, promise: null };
|
|
|
|
}
|
|
|
|
|
|
|
|
async function dbConnect() {
|
|
|
|
if (cached.conn) {
|
|
|
|
return cached.conn;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!cached.promise) {
|
|
|
|
const opts = {
|
|
|
|
useNewUrlParser: true,
|
|
|
|
useUnifiedTopology: true,
|
2023-02-06 13:28:21 -05:00
|
|
|
bufferCommands: false
|
2023-02-05 23:05:07 -05:00
|
|
|
// bufferMaxEntries: 0,
|
|
|
|
// useFindAndModify: true,
|
|
|
|
// useCreateIndex: true
|
|
|
|
};
|
|
|
|
|
2023-02-06 13:28:21 -05:00
|
|
|
mongoose.set('strictQuery', true);
|
2023-02-05 23:05:07 -05:00
|
|
|
cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => {
|
|
|
|
return mongoose;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
cached.conn = await cached.promise;
|
|
|
|
return cached.conn;
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = dbConnect;
|