Setting Up the Connection
Mongoose manages the connection to MongoDB and provides schemas and models on top of it (covered in the MongoDB course). In an Express app, the connection is typically established once, when the server starts.
Connecting on Server Startup
Console Output
Click “Run” to see the console output here.
A User Model
Console Output
Click “Run” to see the console output here.
Using the Model in a Route
Console Output
Click “Run” to see the console output here.
Start the Server Only After Connecting
Calling app.listen() before the database connection resolves means your server could accept requests before it can actually query data — awaiting the connection first avoids a window of broken early requests.
Best Practice
Listen for mongoose connection error events (mongoose.connection.on('error', ...)) even after the initial connection succeeds — a database can become temporarily unreachable at any point during the server's lifetime, not just at startup.