Connect Node.js to MongoDB
Create src/config/database.js.
Import Mongoose and define a reusable connection function.
The application should wait for the database connection before accepting requests that depend on MongoDB.
Mongoose provides mongoose.connect() for establishing the connection.
src/config/database.js
import mongoose from 'mongoose';
export async function connectDatabase() {
const connectionString = process.env.MONGODB_URI;
if (!connectionString) {
throw new Error('MONGODB_URI is not configured');
}
await mongoose.connect(connectionString, {
serverSelectionTimeoutMS: 10000
});
console.log(`MongoDB connected: ${mongoose.connection.name}`);
}
export async function disconnectDatabase() {
await mongoose.disconnect();
}Creates reusable database connection and disconnection functions. The server selection timeout limits how long Mongoose waits to find a suitable MongoDB server.
Key Takeaways
mongoose.connect() establishes the MongoDB connection.
Check required environment variables before connecting.
Separate database lifecycle management from HTTP server initialization.