Subscribe
How to Build a CRUD Application with Node.js and Express.js
7 mins read

By: vishwesh

How to Build a CRUD Application with Node.js and Express.js

If you are new to Node.js and Express.js, you might be wondering how to build a CRUD application with these technologies. In this tutorial, we will walk you through the steps to create a CRUD application using Node.js and Express.js.

What is a CRUD Application?

Before we get started, let's define what a CRUD application is. CRUD stands for Create, Read, Update, and Delete. A CRUD application is an application that allows you to perform these four basic operations on a database. These operations are commonly used in web applications to manage data.

Prerequisites

Before we get started, you will need to have the following installed on your system:

  • Node.js
  • NPM (Node Package Manager)
  • A code editor of your choice (we recommend Visual Studio Code)

Step 1: Create a New Project

The first step is to create a new Node.js project. Open up your terminal and run the following command:

mkdir crud-app
cd crud-app
npm init

This will create a new directory called crud-app, navigate to this directory, and initialize a new Node.js project. You will be prompted to enter some information about your project, such as the name, version, description, and author. You can accept the default values for most of these fields by pressing enter.

Step 2: Install Dependencies

The next step is to install the dependencies that we will need for our application. We will be using the following dependencies:

  • Express.js: a web framework for Node.js
  • Body-parser: a middleware for parsing JSON and urlencoded data
  • Mongoose: an object data modeling (ODM) library for MongoDB
  • Nodemon: a tool for automatically restarting the server when changes are made to the code (dev dependency)

Run the following command to install these dependencies:

npm install express body-parser mongoose nodemon --save

This will install these packages and save them as dependencies in the package.json file.

Step 3: Create the Server

The next step is to create the server using Express.js. Create a new file called index.js in the root of your project and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();
const PORT = process.env.PORT || 3000;

mongoose.connect('mongodb://localhost/crud-app', { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('error', (err) => {
    console.error(err);
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

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

This code imports the necessary packages, creates a new instance of the Express.js app, sets the port to 3000 (or the value of the PORT environment variable), connects to the MongoDB database, and sets up body-parser to parse incoming JSON and urlencoded data.

Step 4: Define the Data Model

The next step is to define the data model for our application using Mongoose. Create a new file called model.js in the root of your project and add the following code:

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    author: {
        type: String,
        required: true
    },
    published_date: {
        type: Date,
        required: true
    },
    pages: {
        type: Number,
        required: true
    },
    genre: {
        type: String,
        required: true
    }
});

const Book = mongoose.model('Book', bookSchema);

module.exports = Book;

This code defines a Mongoose schema for a book, which includes the book's title, author, publication date, number of pages, and genre. The schema is then used to create a Mongoose model called Book, which represents a collection of books in the database.

Step 5: Create the CRUD Routes

The next step is to create the CRUD routes for our application using Express.js. Create a new file called routes.js in the root of your project and add the following code:

const express = require('express');
const router = express.Router();
const Book = require('./model');

router.post('/books', async (req, res) => {
    const book = new Book(req.body);
    try {
        await book.save();
        res.send(book);
    } catch (error) {
        res.status(500).send(error);
    }
});

router.get('/books', async (req, res) => {
    try {
        const books = await Book.find();
        res.send(books);
    } catch (error) {
        res.status(500).send(error);
    }
});

router.get('/books/:id', async (req, res) => {
    const _id = req.params.id;
    try {
        const book = await Book.findById(_id);
        if (!book) {
            return res.status(404).send();
        }
        res.send(book);
    } catch (error) {
        res.status(500).send(error);
    }
});

router.patch('/books/:id', async (req, res) => {
    const _id = req.params.id;
    try {
        const book = await Book.findByIdAndUpdate(_id, req.body, { new: true, runValidators: true });
        if (!book) {
            return res.status(404).send();
        }
        res.send(book);
    } catch (error) {
        res.status(500).send(error);
    }
});

router.delete('/books/:id', async (req, res) => {
    const _id = req.params.id;
    try {
        const book = await Book.findByIdAndDelete(_id);
        if (!book) {
            return res.status(404).send();
        }
        res.send(book);
    } catch (error) {
        res.status(500).send(error);
    }
});

module.exports = router;

This code defines five routes for our application:

  • POST /books: creates a new book in the database
  • GET /books: retrieves all books from the database
  • GET /books/:id: retrieves a specific book from the database by ID
  • PATCH /books/:id: updates a specific book in the database by ID
  • DELETE /books/:id: deletes a specific book from the database by ID

Each route uses the Mongoose model to perform the corresponding operation on the database and sends an appropriate response to the client.

Step 6: Mount the Routes

The final step is to mount the routes in our Express.js application. In the index.js file, add the following code:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const routes = require('./routes');

const app = express();
const port = 3000;

mongoose.connect('mongodb://localhost:27017/books', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true
}).then(() => {
    console.log('Connected to database');
}).catch((error) => {
    console.log(error);
});

app.use(bodyParser.json());

app.use('/api', routes);

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

This code sets up an Express.js application with middleware for parsing JSON request bodies and mounts the routes at the /api path. It also connects to a local MongoDB database using Mongoose and logs a message to the console when the connection is successful.

Testing the Application

To test the application, start the server by running the following command in the terminal:

node index.js

Then, you can use a tool like Postman or cURL to send HTTP requests to the API. Here are some examples:

  • Creating a new book:
POST http://localhost:3000/api/books
Content-Type: application/json

{
    "title": "The Great Gatsby",
    "author": "F. Scott Fitzgerald",
    "published_date": "1925-04-10",
    "pages": 180,
    "genre": "Fiction"
}
  • Retrieving all books:
GET http://localhost:3000/api/books
  • Retrieving a specific book:
GET http://localhost:3000/api/books/{id}

Replace **{id}** with the ID of the book you want to retrieve.

  • Updating a specific book:
PATCH http://localhost:3000/api/books/{id}
Content-Type: application/json

{
    "pages": 200
}

Replace **{id}** with the ID of the book you want to update.

  • Deleting a specific book:
DELETE http://localhost:3000/api/books/{id}

Replace **{id}** with the ID of the book you want to delete.

That's it! You have successfully built a CRUD application with Node.js and Express.js. You can use this as a starting point for building more complex applications or experiment with different frameworks and databases.

Conclusion

In this tutorial, we have learned how to build a CRUD application with Node.js and Express.js. We started by setting up a new project and installing the necessary dependencies. We then defined the data model using Mongoose and created the routes to perform CRUD operations on the data.

Express.js is a powerful framework that makes it easy to build web applications using Node.js. With its extensive middleware system and modular architecture, you can create robust and scalable applications in a short amount of time.

We hope that this tutorial has helped you understand the basics of building a CRUD application with Node.js and Express.js. Remember that this is just the beginning, and there is a lot more to learn. Keep exploring and experimenting, and you'll be amazed at what you can create with these tools!

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories