import mongoose from 'mongoose';
if (!process.env.MONGODB_URI) {
throw new Error('Invalid environment variable: "MONGODB_URI"');
}
const uri = process.env.MONGODB_URI;
export const connectDB = () => {
const existingConnection = mongoose.connections[0].readyState;
if (existingConnection) {
console.log('Use existing MongoDB connection');
return null;
}
try {
mongoose.connect(uri);
console.log('MongoDB connected');
} catch (error) {
return { error: 'MongoDB failed to connect' };
}
};
export default connectDB;
Last active
April 4, 2024 16:34
-
-
Save Catevika/eab8c6c2e6ad98003b3b49ea05bfce61 to your computer and use it in GitHub Desktop.
NEXTJS14 - Connect MongoDB with Mongoose avoiding multiple connections because of Hot Module Replacement
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment