< alishour.dev />

Creating a RESTful API - Part 3 Preview Image

Creating a RESTful API - Part 3

April 30, 2022

A comprehensive guide to integrating MongoDB Atlas with your RESTful API, covering database connection setup, schema modeling with mongoose, and implementing CRUD operations. Perfect for developers looking to add persistent data storage to their Node.js applications.

REST APIs
Node JS
Javascript
Mongo DB

7 min read

Introduction

In the previous two parts of this series, we covered setting up a basic RESTful API and testing it locally. This third part will focus on integrating MongoDB Atlas with our API and using mongoose to manage our database operations.

We'll learn how to:

  • Connect our API to MongoDB Atlas
  • Create and manage database models
  • Implement CRUD operations using mongoose
  • Test our endpoints with real database interactions

Before starting, you'll need:

  • The completed code from Part 2 (available on GitHub)
  • Node.js and npm installed on your machine
  • A code editor (VS Code recommended)
  • Basic understanding of REST APIs and MongoDB concepts

We'll start by installing the necessary packages for MongoDB integration:

npm i dotenv mongoose

These packages will help us:

  • dotenv: Manage environment variables for secure configuration
  • mongoose: Provide a straightforward, schema-based solution for modeling application data

We'll organize our project with the following structure:

  • 📁 routes/ - Route definitions
  • 📁 controllers/ - Business logic
  • 📁 models/ - Database schemas
  • 📁 middleware/ - Custom middleware functions
  • 📁 utils/ - Utility functions
  • 📄 .env - Environment variables

To begin integrating with MongoDB Atlas:

  1. Sign up for a free account at MongoDB Atlas
  2. Create a new shared cluster (free tier)
  3. Set up database access credentials
  4. Configure network access (IP whitelist)
  5. Get your connection string

Setting Up MongoDB Connection

First, create a new file called db.js in your project's root directory. This file will handle the MongoDB connection setup using mongoose:

const mongoose = require('mongoose');

const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI);
    console.log('MongoDB connected successfully');
  } catch (error) {
    console.error('MongoDB connection error:', error);
    process.exit(1);
  }
};

module.exports = connectDB;

Next, we'll create our first schema model to define the structure of our data. Create a new file in the models directory:

Create a file called user.model.js with the following schema definition:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  email: {
    type: String,
    required: true,
    unique: true,
    match: [/.+\@.+\..+/, 'Please enter a valid email']
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('User', userSchema);

This schema defines the structure for our User model with basic validation and required fields. Now we can use this model to interact with our MongoDB database through mongoose.

Implementing CRUD Operations

Now that we have our database connection and model set up, let's implement the CRUD (Create, Read, Update, Delete) operations in our API. We'll create controller functions that utilize our User model to interact with MongoDB.

Create a new file called user.controller.js in your controllers directory:

let's discuss
your ideas