25 lines
756 B
JavaScript
25 lines
756 B
JavaScript
const mongoose = require('mongoose');
|
|
const path = require('path');
|
|
const dotenv = require('dotenv');
|
|
|
|
// Tự động tìm và nạp file .env nằm cùng thư mục với folder config (tức là trong backend/.env)
|
|
dotenv.config({ path: path.join(__dirname, '../.env') });
|
|
|
|
const connectDB = async () => {
|
|
try {
|
|
const dbURI = process.env.MONGODB_URI;
|
|
|
|
if (!dbURI) {
|
|
throw new Error('MONGODB_URI is not defined in .env file');
|
|
}
|
|
|
|
const conn = await mongoose.connect(dbURI);
|
|
console.log(`MongoDB Connected: ${conn.connection.host}`);
|
|
} catch (error) {
|
|
console.error(`Error connecting to MongoDB: ${error.message}`);
|
|
process.exit(1);
|
|
}
|
|
};
|
|
|
|
module.exports = connectDB;
|