Bytes

Performing CRUD Operations

Last Updated: 22nd June, 2023

Introduction

Creating, reading, updating, and deleting (CRUD) are the fundamental operations performed on data in any web application. Understanding how to perform these operations with Node.js is essential for developers working with server-side applications. In this lesson, we will provide a comprehensive guide on performing CRUD operations with Node.js, exploring different techniques, libraries, and best practices to help you build efficient, data-driven applications.

Understanding CRUD Operations

CRUD stands for Create, Read, Update, and Delete. These operations are the backbone of most web applications, as they enable you to interact with data stored in a database. In this guide, we will focus on performing CRUD operations using Node.js and MongoDB as the database, using both the native MongoDB driver and the Mongoose ODM library.

Setting Up the Environment

Before we dive into the CRUD operations, ensure that you have the following prerequisites:

  • Node.js installed on your system
  • MongoDB installed locally or a MongoDB Atlas account
  • A new project folder with the following dependencies installed using npm (Node.js package manager):
npm init -y
npm install express mongodb mongoose body-parser

These dependencies include Express.js (a web application framework), the MongoDB native driver, Mongoose (an ODM library), and body-parser (a middleware to parse incoming request bodies).

Performing CRUD Operations with the MongoDB Native Driver

The MongoDB native driver allows you to interact directly with the MongoDB database using JavaScript within a Node.js environment. Here's a step-by-step guide to perform CRUD operations using the MongoDB native driver:

Connecting to the MongoDB Database

Create a new file named app.js and use the following code snippet to connect to your MongoDB database:

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

const uri = 'mongodb://localhost:27017/myDatabase';
let db;

MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
  if (err) {
    console.error('Error connecting to MongoDB:', err);
    process.exit(1);
  }

  console.log('Connected to MongoDB');
  db = client.db();
});

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

Replace 'mongodb://localhost:27017/myDatabase' with the appropriate connection URI for your MongoDB instance.

Create (Inserting Documents)

To insert a new document into a MongoDB collection, use the insertOne() method:

app.post('/items', (req, res) => {
  const newItem = req.body;

  db.collection('items').insertOne(newItem, (err, result) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while inserting the item.' });
    } else {
      res.status(201).send(result.ops[0]);
    }
  });
});

This code defines a new Express.js route for the POST method at the /items endpoint, which inserts a new item into the items collection using the insertOne() method.

Read (Fetching Documents)

To fetch documents from a MongoDB collection, you can use the find() method to query the collection and return a cursor, which can be converted to an array using the toArray() method:

app.get('/items', (req, res) => {
  db.collection('items').find({}).toArray((err, items) => {
    if (err) {
res.status(500).send({ error: 'An error occurred while fetching items.' });
} else {
res.status(200).send(items);
}
});
});

This code defines a new Express.js route for the GET method at the /items endpoint, which fetches all items from the items collection using the find() method and returns them as an array.

Update (Modifying Documents)

To update a document in a MongoDB collection, you can use the updateOne() method, specifying a filter to match the document and an update operation to perform:

app.put('/items/:id', (req, res) => {
  const itemId = req.params.id;
  const updatedItem = req.body;

  db.collection('items').updateOne({ _id: new MongoClient.ObjectId(itemId) }, { $set: updatedItem }, (err, result) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while updating the item.' });
    } else {
      res.status(200).send(updatedItem);
    }
  });
});

This code defines a new Express.js route for the PUT method at the /items/:id endpoint, which updates the specified item in the items collection using the updateOne() method.

Delete (Removing Documents)

To remove a document from a MongoDB collection, use the deleteOne() method, specifying a filter to match the document:

app.delete('/items/:id', (req, res) => {
  const itemId = req.params.id;

  db.collection('items').deleteOne({ _id: new MongoClient.ObjectId(itemId) }, (err, result) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while deleting the item.' });
    } else {
      res.status(200).send({ message: 'Item successfully deleted.' });
    }
  });
});

This code defines a new Express.js route for the DELETE method at the /items/:id endpoint, which removes the specified item from the items collection using the deleteOne() method.

Performing CRUD Operations with Mongoose

Mongoose is an Object Data Modeling (ODM) library for MongoDB that provides a higher level of abstraction and more advanced features for working with data. Here's a step-by-step guide to perform CRUD operations using Mongoose:

Connecting to the MongoDB Database and Defining a Schema

First, create a new file named app.js and use the following code snippet to connect to your MongoDB database and define a Mongoose schema:

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

const app = express();
app.use(bodyParser.json());

const uri = 'mongodb://localhost:27017/myDatabase';

mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false });

const itemSchema = new mongoose.Schema({
  name: String,
  description: String,
  price: Number,
});

const Item = mongoose.model('Item', itemSchema);

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

Replace 'mongodb ://localhost:27017/myDatabase' with the appropriate connection URI for your MongoDB instance.

Create (Inserting Documents)

To insert a new document into a MongoDB collection using Mongoose, create a new instance of the model and call the save() method:

app.post('/items', (req, res) => {
  const newItem = new Item(req.body);

  newItem.save((err, savedItem) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while inserting the item.' });
    } else {
      res.status(201).send(savedItem);
    }
  });
});

This code defines a new Express.js route for the POST method at the /items endpoint, which inserts a new item into the items collection using the save() method.

Read (Fetching Documents)

To fetch documents from a MongoDB collection using Mongoose, you can use the find() method on the model:

app.get('/items', (req, res) => {
  Item.find({}, (err, items) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while fetching items.' });
    } else {
      res.status(200).send(items);
    }
  });
});

This code defines a new Express.js route for the GET method at the /items endpoint, which fetches all items from the items collection using the find() method.

Update (Modifying Documents)

To update a document in a MongoDB collection using Mongoose, you can use the findByIdAndUpdate() method on the model:

app.put('/items/:id', (req, res) => {
  const itemId = req.params.id;
  const updatedItem = req.body;

  Item.findByIdAndUpdate(itemId, updatedItem, { new: true }, (err, updatedDocument) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while updating the item.' });
    } else {
      res.status(200).send(updatedDocument);
    }
  });
});

This code defines a new Express.js route for the PUT method at the /items/:id endpoint, which updates the specified item in the items collection using the findByIdAndUpdate() method.

Delete (Removing Documents)

To remove a document from a MongoDB collection using Mongoose, use the findByIdAndRemove() method on the model:

app.delete('/items/:id', (req, res) => {
  const itemId = req.params.id;

  Item.findByIdAndRemove(itemId, (err, result) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while deleting the item.' });
    } else {
      res.status(200).send({ message: 'Item successfully deleted.' });
    }
  });
});

This code defines a new Express.js route for the DELETE method at the /items/:id endpoint, which removes the specified item from the items collection using the findByIdAndRemove() method.

Conclusion

In this article, we covered how to perform CRUD operations with Node.js and MongoDB using both the native MongoDB driver and the Mongoose ODM library. Understanding and implementing these operations is essential for developers building server-side applications. By mastering CRUD operations with Node.js, you will be better equipped to create efficient, data-driven applications.

Module 7: Working with DatabasesPerforming CRUD Operations

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter