Day 3: Connecting to a MongoDB Database


In this tutorial, you’ll learn how to connect your Express API to a MongoDB database using Mongoose, an ODM (Object Data Modeling) library for MongoDB. By the end of today’s lesson, you’ll have set up MongoDB, created models, and persisted data to the database.


What You Will Learn Today:

  1. Installing and setting up MongoDB
  2. Connecting the API to MongoDB with Mongoose
  3. Creating models for MongoDB collections
  4. Writing API routes to interact with the database
  5. Testing the API with Postman

Step 1: Installing and Setting Up MongoDB

You’ll need to install MongoDB locally or use a cloud solution like MongoDB Atlas. In this tutorial, we’ll focus on using MongoDB Atlas, a cloud-hosted version of MongoDB.

Creating a MongoDB Atlas Account

  1. Go to the MongoDB Atlas website and sign up for a free account.
  2. After signing up, create a new Cluster. This will host your MongoDB database.
  3. Choose the free tier for your cluster, and select the cloud provider and region.
  4. Once your cluster is ready, click Connect and select Connect Your Application.
  5. MongoDB Atlas will provide you with a connection string. Copy the connection string, as you will need it to connect to your database from the Express API.

Example connection string:

mongodb+srv://<username>:<password>@cluster0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

Replace <username>, <password>, and myFirstDatabase with your actual database details.

See also  Guide to download files from WSL (Windows Subsystem for Linux) to your Windows machine using Visual Studio Code

Step 2: Installing Mongoose

Mongoose is a popular ODM library that allows you to interact with MongoDB from Node.js.

  1. Install Mongoose in your project by running the following command in your project directory:
npm install mongoose

Step 3: Connecting to MongoDB

Now that we have Mongoose installed, let’s connect our API to MongoDB.

  1. Open index.js and modify it to include the MongoDB connection:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 5000;

// MongoDB connection string
const mongoURI = 'mongodb+srv://<username>:<password>@cluster0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';

// Connect to MongoDB
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch((err) => console.log('MongoDB connection error:', err));

// Middleware to parse JSON
app.use(express.json());

// Import the user routes
const userRoutes = require('./routes/users');
app.use('/api/users', userRoutes);

// Basic route for the home page
app.get('/', (req, res) => {
  res.send('Welcome to my Express API with MongoDB!');
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Explanation:

  • mongoose.connect(): This connects your Node.js app to MongoDB using the connection string you got from MongoDB Atlas.
  • Middleware: We’ve added express.json() to allow the app to parse JSON bodies in incoming requests.
  • Replace <username>, <password>, and myFirstDatabase with your actual MongoDB Atlas credentials.

Step 4: Creating a User Model

With the connection to MongoDB established, let’s create a User model to represent user documents in the database. In MongoDB, data is stored in collections (similar to tables in relational databases), and each document is represented by a model.

Creating the Models Directory

  1. Inside your project directory, create a folder called models. This folder will hold all the Mongoose models for your database.
mkdir models
  1. Inside the models folder, create a new file called User.js:
touch models/User.js
  1. Open models/User.js and define the User schema and model:
const mongoose = require('mongoose');

// Define the user schema
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  age: {
    type: Number,
    required: false
  }
});

// Create the User model
const User = mongoose.model('User', userSchema);

module.exports = User;

Explanation:

  • mongoose.Schema(): Defines the schema for the user, which specifies the structure of user documents in the database.
  • User model: This represents the user collection in MongoDB.
See also  Day 2: Building and Customizing the User Interface (UI)

Step 5: Writing API Routes to Interact with MongoDB

Now that we have the User model set up, let’s create API routes to interact with the database. We’ll create routes to add new users, retrieve users, and delete users.

Adding a New User

  1. Open routes/users.js and add the following POST route to create a new user:
const express = require('express');
const router = express.Router();
const User = require('../models/User');
const userController = require('../controllers/userController');

// Get all users
router.get('/', userController.getAllUsers);

// Get a user by ID
router.get('/:id', userController.getUserById);

// Add a new user
router.post('/', async (req, res) => {
  try {
    const { name, email, age } = req.body;
    const newUser = new User({ name, email, age });
    const savedUser = await newUser.save();
    res.status(201).json(savedUser);
  } catch (error) {
    res.status(400).json({ message: 'Error creating user', error });
  }
});

module.exports = router;

Explanation:

  • POST /api/users: This route allows the client to add a new user by sending a POST request with the user data (name, email, age).
  • new User(): Creates a new instance of the User model.
  • newUser.save(): Saves the new user to the MongoDB database.
  • Error Handling: If there’s an error (e.g., missing required fields or duplicate emails), the server responds with a 400 status code.

Step 6: Testing the API with Postman

Now that we have the POST route set up, let’s test the API by adding new users.

  1. Restart the server by running:
node index.js
  1. Open Postman and perform the following test:
  • Add a new user:
    • Set the request type to POST.
    • URL: http://localhost:5000/api/users
    • In the Body tab, select raw and set the format to JSON.
    • Enter the following JSON data:
{
  "name": "John Doe",
  "email": "[email protected]",
  "age": 30
}
  1. Click Send. You should receive a response with the newly created user:
{
  "_id": "60f74c47e49b2f001ffb7510",
  "name": "John Doe",
  "email": "[email protected]",
  "age": 30,
  "__v": 0
}

This confirms that the new user has been added to the MongoDB database.

See also  Security Considerations in Migrations

Step 7: Retrieving Users from MongoDB

Now, let’s modify the getAllUsers controller to fetch users from the MongoDB database instead of the hardcoded array.

  1. Open controllers/userController.js and modify the getAllUsers function:
const User = require('../models/User');

// Controller to get all users
exports.getAllUsers = async (req, res) => {
  try {
    const users = await User.find(); // Fetch all users from the database
    res.json(users);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching users', error });
  }
};

// Controller to get a user by ID
exports.getUserById = async (req, res) => {
  try {
    const user = await User.findById(req.params.id); // Fetch user by ID
    if (user) {
      res.json(user);
    } else {
      res.status(404).json({ message: 'User not found' });
    }
  } catch (error) {
    res.status(500).json({ message: 'Error fetching user', error });
  }
};

Explanation:

  • User.find(): Fetches all user documents from the MongoDB collection.
  • User.findById(): Fetches a single user by their ID.

Now, when you make a GET request to

/api/users, it will return all the users stored in MongoDB.


Step 8: Recap and Summary

In this tutorial, you learned how to connect your Express API to a MongoDB database and interact with it using Mongoose. Here’s a quick summary of what you’ve done:

  • Created a MongoDB database using MongoDB Atlas.
  • Installed and set up Mongoose to connect your Node.js app to MongoDB.
  • Created a Mongoose model to define the structure of user documents.
  • Wrote API routes to add and retrieve users from the database.
  • Tested the API using Postman to ensure the data is persisted in the database.

With the database connected, you can now store, retrieve, and manipulate real data!


Next Up: Day 4 – Authentication Using JWT

In Day 4, we’ll add authentication to your API using JWT (JSON Web Tokens). You’ll learn how to protect routes, register and log in users, and generate tokens for secure access.

Stay tuned for more advanced features tomorrow!


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.