00c68f3870
I've been playing around with `examples/with-mongodb-mongoose` and this PR updates mongoose and swr which are severely outdated to their most recent major releases. This PR also removes two options that are no longer needed in the connection configuration when using mongoose 6: `useNewUrlParser` and `useUnifiedTopology`. See [Migrating from 5.x to 6.x - No More Deprecation Warning Options](https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options). ## Documentation / Examples - [x] Make sure the linting passes
40 lines
837 B
JavaScript
40 lines
837 B
JavaScript
import mongoose from 'mongoose'
|
|
|
|
const MONGODB_URI = process.env.MONGODB_URI
|
|
|
|
if (!MONGODB_URI) {
|
|
throw new Error(
|
|
'Please define the MONGODB_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 = {
|
|
bufferCommands: false,
|
|
}
|
|
|
|
cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
|
|
return mongoose
|
|
})
|
|
}
|
|
cached.conn = await cached.promise
|
|
return cached.conn
|
|
}
|
|
|
|
export default dbConnect
|