How to Use MongoDB with Express.js

In this tutorial, we will learn how to use MongoDB with Express.js, a popular web application framework for Node.js. MongoDB is a NoSQL document database that provides high performance, scalability, and flexibility for building web applications. Combining MongoDB with Express.js allows us to easily store and retrieve data from a database in our Express.js application.

Prerequisites

Before we begin, make sure you have the following installed on your system:

You can install these dependencies by following their respective installation guides.

Setting Up the Express.js Application

First, let’s create a new directory for our Express.js application and navigate into it:

mkdir express-mongodb-app
cd express-mongodb-app

Initialize a new Node.js project by running the following command:

npm init -y

This will create a package.json file in the current directory.

Next, let’s install Express.js as a dependency for our project:

npm install express

Now, let’s create a new file called index.js in our project directory. This will be the main entry point for our Express.js application.

Open index.js in a text editor and add the following code:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

This code sets up a basic Express.js application that listens for incoming HTTP requests on port 3000 and responds with “Hello World!” when the root URL (/) is accessed.

Now, let’s start our Express.js application by running the following command:

node index.js

You should see the message “Server started on port 3000” printed in the console, indicating that your Express.js application is running.

Open your web browser and navigate to `http://localhost:3000`. You should see the “Hello World!” message displayed in your browser.

Connecting to MongoDB

Now that we have our Express.js application up and running, let’s connect it to a MongoDB database.

First, make sure you have MongoDB running on your system. You can start it by running the mongod command in a separate terminal window:

mongod

Next, let’s install the official MongoDB driver for Node.js as a dependency for our project:

npm install mongodb

Now, let’s create a new file called db.js in our project directory. This file will contain the code for connecting to the MongoDB database.

Open db.js in a text editor and add the following code:

const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';
const dbName = 'myapp';

let client;

async function connect() {
  try {
    // Connect to MongoDB
    client = await MongoClient.connect(url, { useUnifiedTopology: true });

    console.log('Connected to MongoDB');

    // Access the database
    const db = client.db(dbName);

    return db;
  } catch (err) {
    console.error('Error connecting to MongoDB', err);
    throw err;
  }
}

function disconnect() {
  // Close the MongoDB connection
  client.close();

  console.log('Disconnected from MongoDB');
}

module.exports = {
  connect,
  disconnect,
};

This code defines two functions: connect() and disconnect(). The connect() function establishes a connection to the MongoDB database using the MongoClient.connect() method. It returns the database object that we can use to interact with the database. The disconnect() function closes the MongoDB connection.

Next, open index.js in a text editor and require the db.js file at the top of the file:

const express = require('express');
const { connect, disconnect } = require('./db');

...

Now, let’s update the / route handler to connect to the MongoDB database and retrieve some data.

Replace the existing code inside the / route handler with the following code:

app.get('/', async (req, res) => {
  try {
    // Connect to MongoDB
    const db = await connect();

    // Get data from the "users" collection
    const users = await db.collection('users').find().toArray();

    // Send the data as a JSON response
    res.json(users);

    // Disconnect from MongoDB
    disconnect();
  } catch (err) {
    console.error('Error handling request', err);
    res.status(500).send('Internal Server Error');
  }
});

This code retrieves all documents from the users collection in the MongoDB database and sends them as a JSON response.

Now, start your Express.js application by running the following command:

node index.js

Open your web browser and navigate to http://localhost:3000`. You should see a JSON response containing the documents from theusers` collection in your MongoDB database.

Inserting Data into MongoDB

Now that we are able to retrieve data from MongoDB, let’s learn how to insert data into the database.

First, let’s update the / route handler in index.js to insert a new document into the users collection before retrieving the data.

Replace the existing code inside the / route handler with the following code:

app.get('/', async (req, res) => {
  try {
    // Connect to MongoDB
    const db = await connect();

    // Insert a new document into the "users" collection
    await db.collection('users').insertOne({ name: 'John Doe', age: 30 });

    // Get data from the "users" collection
    const users = await db.collection('users').find().toArray();

    // Send the data as a JSON response
    res.json(users);

    // Disconnect from MongoDB
    disconnect();
  } catch (err) {
    console.error('Error handling request', err);
    res.status(500).send('Internal Server Error');
  }
});

This code inserts a new document with the fields name and age into the users collection before retrieving the data.

Start your Express.js application and open your web browser. Navigate to `http://localhost:3000` to see the updated JSON response containing the newly inserted document.

Updating and Deleting Data

In addition to inserting data, MongoDB also provides methods for updating and deleting data.

Let’s update our Express.js application to demonstrate how to update and delete documents in the MongoDB database.

Open index.js in a text editor and update the / route handler as follows:

app.get('/', async (req, res) => {
  try {
    // Connect to MongoDB
    const db = await connect();

    // Insert a new document into the "users" collection
    await db.collection('users').insertOne({ name: 'John Doe', age: 30 });

    // Update the name of the first document in the "users" collection
    await db.collection('users').updateOne({}, { $set: { name: 'Jane Doe' } });

    // Delete the last document from the "users" collection
    await db.collection('users').deleteOne({});

    // Get data from the "users" collection
    const users = await db.collection('users').find().toArray();

    // Send the data as a JSON response
    res.json(users);

    // Disconnect from MongoDB
    disconnect();
  } catch (err) {
    console.error('Error handling request', err);
    res.status(500).send('Internal Server Error');
  }
});

This code demonstrates how to update and delete documents in the users collection. It updates the name of the first document to “Jane Doe” using the $set operator and deletes the last document from the collection using the deleteOne() method.

Start your Express.js application and open your web browser. Navigate to `http://localhost:3000` to see the updated JSON response containing the modified data.

Conclusion

In this tutorial, we learned how to use MongoDB with Express.js to store and retrieve data from a database in our Express.js application. We learned how to connect our application to a MongoDB database, insert data into the database, retrieve data from the database, and update and delete data in the database. MongoDB provides a simple and flexible way to persist data in our Express.js applications, allowing us to build powerful and scalable web applications.

You can find the complete source code for this tutorial on GitHub.

I hope you found this tutorial helpful! If you have any questions or feedback, please feel free to reach out.

Happy coding!

Related Post