Unverified Commit 4e27e00c authored by mustafaKamal-fe's avatar mustafaKamal-fe Committed by GitHub

Update dbConnect.js (#19644)

* Update dbConnect.js

The previous logic was in my opinion prone to errors in situations when different calls to this function from different locations may happen at the same time ( like a race condition  ). If the readyState is anything but not 0, then we must not try to perform a new connection as this may cause consequent connections!

I hope this makes sense

* Update examples/with-mongodb-mongoose/utils/dbConnect.js

* Lint fix and minor changes
Co-authored-by: 's avatarLuis Alvarez D <luis@vercel.com>
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent ec430ea7
/* This is a database connection function*/
import mongoose from 'mongoose' import mongoose from 'mongoose'
const connection = {} /* creating connection object*/
async function dbConnect() { async function dbConnect() {
/* check if we have connection to our databse*/ // check if we have a connection to the database or if it's currently
if (connection.isConnected) { // connecting or disconnecting (readyState 1, 2 and 3)
if (mongoose.connection.readyState >= 1) {
return return
} }
/* connecting to our database */ return mongoose.connect(process.env.MONGODB_URI, {
const db = await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true, useNewUrlParser: true,
useUnifiedTopology: true, useUnifiedTopology: true,
useFindAndModify: false, useFindAndModify: false,
}) })
connection.isConnected = db.connections[0].readyState
} }
export default dbConnect export default dbConnect
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment