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:
- Node.js (https://nodejs.org)
- MongoDB (https://mongodb.com)
- Express.js (https://expressjs.com)
Setting up the project
-
First, create a new directory for your project and navigate into it.
mkdir mongo-crud-tutorial cd mongo-crud-tutorial
-
Initialize a new Node.js project using the following command:
npm init -y
-
Install the necessary dependencies for our project:
npm install express mongodb
- Create a new file named
index.js
and open it in your favorite code editor.
Connecting to MongoDB
- 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);
});
});
- This code defines a
GET
endpoint/users/:id
that fetches a user with a specific ID from the MongoDB collectionusers
.
Preparing data for update
-
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' }); }); });
- This code defines a
PUT
endpoint/users/:id
that updates a user with a specific ID in the MongoDB collectionusers
. 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!