file & doc: create monggose in the lib folder and added functions to invoke database connection

This commit is contained in:
Leon Xu committed 2023-12-30 13:48:03 -08:00
1 parent f5f8f18a38
commit 85f2d80bc9
1 file changed
+20
+20
View File
@@ -0,0 +1,20 @@
import mongoose from 'mongoose';
let isConnected = false; // Variable to track the connection status
export const connectToDB = async () => {
mongoose.set('strictQuery', true);
if (!process.env.MONGODB_URI) return console.log('Unable to connect to the database');
if (isConnected) return console.log('=> connected using existing database connection');
try {
await mongoose.connect(process.env.MONGODB_URI);
isConnected = true;
console.log('Connected to the database');
} catch (error) {
console.log(error);
}
}