DEV Community

Cover image for โœ… How to Use MongoDB with Express.js
Ilyas Abdisalam
Ilyas Abdisalam

Posted on

โœ… How to Use MongoDB with Express.js

๐Ÿ“˜ Overview

This guide shows you how to connect a MongoDB database to an Express.js application using the official mongodb driver. This is useful for developers building full-stack JavaScript applications that need to store and retrieve data.


๐Ÿง  Prerequisites

Before you begin, make sure you have:

  • Node.js and npm installed
  • MongoDB installed locally or a MongoDB Atlas cloud database
  • Basic knowledge of JavaScript and Express.js

๐Ÿ› ๏ธ Step 1: Create a New Express App

A. Create a new project folder:

mkdir express-mongo-app cd express-mongo-app 
Enter fullscreen mode Exit fullscreen mode

B. Initialize a Node.js project:

npm init -y npm install express mongodb 
Enter fullscreen mode Exit fullscreen mode

C. Create an index.js file with this boilerplate:

// CommonJS (used in Node.js by default, not ES6 module) const express = require('express'); const app = express(); const port = 3000; app.use(express.json()); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); }); 
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”Œ Step 2: Connect to MongoDB

A. At the top of index.js, import the MongoDB client:

const { MongoClient } = require('mongodb'); 
Enter fullscreen mode Exit fullscreen mode

B. Define your connection URL and database name:

const uri = 'mongodb://localhost:27017'; // Replace with your MongoDB Atlas URI if using cloud const client = new MongoClient(uri); const dbName = 'myDatabase'; 
Enter fullscreen mode Exit fullscreen mode

C. Create an async function to connect:

async function run() { try { await client.connect(); console.log('Connected successfully to MongoDB'); const db = client.db(dbName); const collection = db.collection('users'); // Sample route to insert a user app.post('/users', async (req, res) => { const user = req.body; const result = await collection.insertOne(user); res.send(result); }); // Sample route to get all users app.get('/users', async (req, res) => { const users = await collection.find({}).toArray(); res.send(users); }); } catch (err) { console.error(err); } } run(); 
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ Step 3: Test the App

A. Start the server:

node index.js 
Enter fullscreen mode Exit fullscreen mode

B. Use Postman or curl to test endpoints:

  • Insert a user:
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "Mohamed", "email": "Mohamed@gmail.com"}' 
Enter fullscreen mode Exit fullscreen mode
  • Get all users:
curl http://localhost:3000/users 
Enter fullscreen mode Exit fullscreen mode

๐Ÿงผ Step 4: Clean Up and Best Practices

  • Store your MongoDB URI in an environment variable (e.g., .env)
  • Handle connection errors and cleanup with process.on('SIGINT')
  • Use async/await consistently for clarity

โœ… Summary

Youโ€™ve learned how to:

  • Set up a Node.js + Express.js app
  • Connect to MongoDB (local or Atlas)
  • Insert and retrieve data with API endpoints

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.