How to Use MongoDB Atlas with Node.js and Express.js

MongoDB is a popular NoSQL database that provides high performance, scalability, and flexibility to store and retrieve structured and unstructured data. MongoDB Atlas is a fully-managed cloud database service that allows you to deploy, scale, and manage MongoDB clusters with ease. In this tutorial, we will learn how to use MongoDB Atlas with Node.js and Express.js to build a RESTful API.

Prerequisites

To follow along with this tutorial, you will need the following:

Creating a MongoDB Atlas Cluster

Before we can start using MongoDB Atlas with Node.js and Express.js, we need to create a MongoDB Atlas cluster.

  1. Sign in to your MongoDB Atlas account.
  2. Click on the “Build a Cluster” button to create a new cluster.

  3. Select your preferred cloud provider and region, then choose the cluster tier and additional settings according to your requirements.

  4. Click on the “Create Cluster” button to start creating the cluster. It may take a few minutes for the cluster to be provisioned.

  5. Once the cluster is created, click on the “Connect” button.

  6. In the “Connect to Cluster” dialog, click on “Connect your application”.

  7. Choose the Node.js driver version, then copy the connection string.

Setting Up a Node.js and Express.js Project

Now that we have our MongoDB Atlas cluster ready, let’s set up a Node.js and Express.js project.

  1. Create a new directory for your project:
    mkdir mongodb-atlas-nodejs-express
    cd mongodb-atlas-nodejs-express
    
  2. Initialize a new npm project by running the following command and following the prompts:
    npm init
    

    This will create a package.json file in your project directory.

  3. Install the required dependencies:

    npm install express mongodb dotenv
    
  • express is a fast, unopinionated, minimalist web framework for Node.js.
  • mongodb is the official MongoDB driver for Node.js.
  • dotenv loads environment variables from a .env file into process.env.
  1. Set up the project structure:
    touch server.js
    mkdir config models routes
    touch config/db.js models/book.js routes/book.js
    
  2. Create a .env file in the root of your project directory and add the MongoDB Atlas connection string:
    MONGODB_URI=<your-mongodb-atlas-connection-string>
    

    Replace <your-mongodb-atlas-connection-string> with the connection string you copied from MongoDB Atlas earlier.

  3. Open server.js and add the following code:

    const express = require('express');
    const dotenv = require('dotenv');
    const db = require('./config/db');
    const bookRoutes = require('./routes/book');
    
    // Load environment variables from .env file
    dotenv.config();
    
    // Create Express app
    const app = express();
    
    // Connect to MongoDB
    db.connect();
    
    // Parse JSON request bodies
    app.use(express.json());
    
    // Use book routes
    app.use('/api/books', bookRoutes);
    
    // Start the server
    const port = process.env.PORT || 3000;
    app.listen(port, () => {
     console.log(`Server running on port ${port}`);
    });
    
  4. Open config/db.js and add the following code:
    const mongodb = require('mongodb');
    
    function connect() {
     mongodb.connect(process.env.MONGODB_URI, {
       useNewUrlParser: true,
       useUnifiedTopology: true,
     })
       .then((client) => {
         console.log('Connected to MongoDB');
         // Do something with the MongoDB client
       })
       .catch((error) => {
         console.error('Failed to connect to MongoDB', error);
         process.exit(1);
       });
    }
    
    module.exports = { connect };
    
  5. Open models/book.js and add the following code:
    const mongodb = require('mongodb');
    
    class Book {
     constructor(title, author) {
       this.title = title;
       this.author = author;
     }
    
     static findAll() {
       const db = mongodb.connection.db;
       return db.collection('books').find().toArray();
     }
    
     static create(book) {
       const db = mongodb.connection.db;
       return db.collection('books').insertOne(book);
     }
    }
    
    module.exports = Book;
    
  6. Open routes/book.js and add the following code:
    const express = require('express');
    const router = express.Router();
    const Book = require('../models/book');
    
    router.get('/', async (req, res) => {
     try {
       const books = await Book.findAll();
       res.json(books);
     } catch (error) {
       res.status(500).json({ error: 'An error occurred' });
     }
    });
    
    router.post('/', async (req, res) => {
     const book = new Book(req.body.title, req.body.author);
    
     try {
       const result = await Book.create(book);
       res.json(result.ops[0]);
     } catch (error) {
       res.status(500).json({ error: 'An error occurred' });
     }
    });
    
    module.exports = router;
    

Testing the API

With everything set up, we can now test the API.

  1. Start the server:
    node server.js
    

    You should see the following message indicating that the server is running:

    Server running on port 3000
    
  2. Use a tool like cURL or Postman to make HTTP requests to the API.
  • To get a list of books, send a GET request to `http://localhost:3000/api/books`.
  • To create a new book, send a POST request to http://localhost:3000/api/books` with a JSON body containing thetitleandauthor` properties.

    For example, using cURL:

    curl -X GET http://localhost:3000/api/books
    
    curl -X POST -H "Content-Type: application/json" -d '{"title":"Book Title","author":"Book Author"}' http://localhost:3000/api/books
    

    You should receive a JSON response with the list of books or the created book.

  1. You can also use a MongoDB client like MongoDB Compass to connect to your MongoDB Atlas cluster and view and manage the data directly.

Conclusion

In this tutorial, we learned how to use MongoDB Atlas with Node.js and Express.js to build a RESTful API. We set up a MongoDB Atlas cluster, created a Node.js and Express.js project, connected to MongoDB Atlas, defined a Book model, and implemented routes to handle CRUD operations on books. Now you can leverage the power of MongoDB Atlas to store and retrieve data in your Node.js and Express.js applications.

Related Post