Complete Tutorial on Creating a RESTful API with Node.js and MongoDB – Retrieve Data By Id (#15)

Posted by

RESTful API using Node Js MongoDB – GET By Id – #15 – Complete MongoDB Tutorial

RESTful API using Node Js MongoDB – GET By Id

In this tutorial, we will be learning how to create a RESTful API using Node.js and MongoDB. We will specifically focus on the GET request by ID, which is an essential operation when working with databases.

Prerequisites

Before we begin, make sure you have Node.js and MongoDB installed on your machine. You can download and install them from their official websites if you haven’t already.

Setting up the Project

First, create a new folder for your project and navigate to it using the terminal. Then, run the following command to initialize a new Node.js project:


npm init -y

Next, install the necessary dependencies using the following command:


npm install express mongoose

This will install the Express framework for building the API and the Mongoose library for interacting with the MongoDB database.

Creating the API Endpoint

After setting up the project, create a new file called ‘app.js’ and add the following code:


const express = require('express');
const mongoose = require('mongoose');
const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });

// Define a schema for the document
const userSchema = new mongoose.Schema({
name: String,
email: String
});

// Create a model based on the schema
const User = mongoose.model('User', userSchema);

// GET request by ID
app.get('/users/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
res.json(user);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});

This code sets up the Express server, connects to the MongoDB database, defines a user schema, creates a model, and adds a GET endpoint to retrieve a user by their ID.

Testing the API

To test the API, run the following command in the terminal:


node app.js

Then, open a web browser or a tool like Postman and make a GET request to ‘http://localhost:3000/users/15′, where ’15’ is the ID of the user you want to retrieve. You should receive a JSON response with the user’s information.

Conclusion

Congratulations! You have successfully created a RESTful API using Node.js and MongoDB to handle GET requests by ID. You can now use this knowledge to expand your API by adding more endpoints and functionalities.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@nabilshartaj2030
6 months ago

nice tutorial brother! keep it coming because i am waiting for your tutorials