DevAcademy
LearnNode.jsConnecting to MongoDB
AdvancedNode.js

Connecting to MongoDB

Connect a Node.js/Express app to MongoDB using Mongoose.

Reading Time

14 min

Lesson

Lesson 27 of 34

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

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

A User Model

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Using the Model in a Route

Try it yourself — edit and run

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.

Interview Questions

Quick Quiz

1. Why start app.listen() only after the database connection succeeds?

2. What does mongoose.model() create?

3. Why listen for connection error events even after the initial connection succeeds?