,

MongoDB CRUD Operations: Retrieving and Preparing Data for Updates in a Node.js Express.js Tutorial by Mozzammel Ridoy

Posted by


In this tutorial, we will cover the basics of CRUD operations in MongoDB using Node.js and Express.js. Specifically, we will focus on fetching and preparing data for updates. This tutorial is aimed at beginners who are looking to learn how to work with MongoDB and Node.js.

Prerequisites

Before we begin, make sure you have the following prerequisites installed on your system:

Setting up the project

  1. First, create a new directory for your project and navigate into it.

    mkdir mongo-crud-tutorial
    cd mongo-crud-tutorial
  2. Initialize a new Node.js project using the following command:

    npm init -y
  3. Install the necessary dependencies for our project:

    npm install express mongodb
  4. Create a new file named index.js and open it in your favorite code editor.

Connecting to MongoDB

  1. In order to interact with MongoDB, we need to establish a connection to the database. Add the following code snippet to index.js:
    
    const express = require('express');
    const MongoClient = require('mongodb').MongoClient;

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

const url = ‘mongodb://localhost:27017’;
const dbName = ‘mydb’;

MongoClient.connect(url, (err, client) => {
if (err) {
console.error(‘Error connecting to MongoDB:’, err);
return;
}

app.locals.db = client.db(dbName);
app.listen(PORT, () => {
console.log(Server is running on http://localhost:${PORT});
});
});


2. This code establishes a connection to a MongoDB database called `mydb` running on `localhost` at port `27017`.

## Fetching data for update
1. Now let's create an API endpoint that fetches data from MongoDB for update. Add the following code snippet to `index.js`:
```javascript
app.get('/users/:id', (req, res) => {
  const db = req.app.locals.db;

  db.collection('users').findOne({ _id: parseInt(req.params.id) }, (err, result) => {
    if (err) {
      console.error(err);
      res.status(500).json({ error: 'Internal server error' });
      return;
    }

    if (!result) {
      res.status(404).json({ error: 'User not found' });
      return;
    }

    res.json(result);
  });
});
  1. This code defines a GET endpoint /users/:id that fetches a user with a specific ID from the MongoDB collection users.

Preparing data for update

  1. Now let’s create an API endpoint that prepares data for update. Add the following code snippet to index.js:

    app.put('/users/:id', express.json(), (req, res) => {
    const db = req.app.locals.db;
    
    db.collection('users').updateOne({ _id: parseInt(req.params.id) }, { $set: req.body }, (err, result) => {
    if (err) {
      console.error(err);
      res.status(500).json({ error: 'Internal server error' });
      return;
    }
    
    if (result.matchedCount === 0) {
      res.status(404).json({ error: 'User not found' });
      return;
    }
    
    res.json({ message: 'User updated successfully' });
    });
    });
  2. This code defines a PUT endpoint /users/:id that updates a user with a specific ID in the MongoDB collection users. The request body contains the data to be updated.

Conclusion

In this tutorial, we covered the basics of performing CRUD operations in MongoDB using Node.js and Express.js. We specifically focused on fetching and preparing data for updates. We hope this tutorial was helpful for beginners looking to work with MongoDB and Node.js. If you have any further questions or need additional help, don’t hesitate to reach out. Happy coding!

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x