-
Notifications
You must be signed in to change notification settings - Fork 45
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #40 from Shu12388y/main
resolve the database connection
- Loading branch information
Showing
1 changed file
with
12 additions
and
38 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,41 +1,15 @@ | ||
import mongoose from "mongoose"; | ||
|
||
const MONGODB_URI = process.env.MONGO_URI; | ||
|
||
if (!MONGODB_URI) { | ||
throw new Error('Please define the MONGO_URI environment variable inside .env.local'); | ||
} | ||
|
||
let cached = global.mongoose; | ||
|
||
if (!cached) { | ||
cached = global.mongoose = { conn: null, promise: null }; | ||
} | ||
|
||
export async function dbConnect() { | ||
if (cached.conn) { | ||
console.log("Using cached database connection."); | ||
return cached.conn; | ||
try { | ||
mongoose.connect(process.env.MONGO_URI!); | ||
const connection = mongoose.connection; | ||
connection.on("connected", () => { | ||
console.log("Database connected"); | ||
}); | ||
connection.on("error", (err) => { | ||
console.log("error: ", err); | ||
}); | ||
} catch (error: any) { | ||
console.log(error); | ||
} | ||
|
||
if (!cached.promise) { | ||
const opts = { | ||
useNewUrlParser: true, | ||
useUnifiedTopology: true, | ||
bufferCommands: false, | ||
}; | ||
|
||
cached.promise = mongoose.connect(MONGODB_URI, opts) | ||
.then((mongooseInstance) => { | ||
console.log("Database connected successfully."); | ||
return mongooseInstance; | ||
}) | ||
.catch((err) => { | ||
console.error("Database connection error: ", err); | ||
throw new Error(`Database connection failed: ${err.message}`); | ||
}); | ||
} | ||
|
||
cached.conn = await cached.promise; | ||
return cached.conn; | ||
} | ||
} |