Complete MongoDB Tutorial – Part 15
In this tutorial, we will be learning how to create a RESTful API using Node.js and MongoDB to retrieve all items from a database. We will be using HTTP GET method to fetch all the items from the MongoDB database.
Setting up Node.js and MongoDB
Before we start creating the API, make sure you have Node.js and MongoDB installed on your system. You can download and install them from their respective official websites.
Creating a Node.js project
Create a new directory for your project and run the following command to initialize a new Node.js project:
$ mkdir restful-api
$ cd restful-api
$ npm init -y
Installing necessary packages
Now, we need to install the necessary packages for our Node.js project. Run the following command to install Express and Mongoose:
$ npm install express mongoose
Creating the server.js file
Create a new file called server.js and add the following code to create an Express server and connect to the MongoDB database:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
const Item = mongoose.model('Item', { name: String });
app.get('/items', async (req, res) => {
const items = await Item.find();
res.json(items);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Testing the API
Now you can test the API by sending a GET request to http://localhost:3000/items. This will retrieve all the items from the database and return them as a JSON response.
That’s it! You have successfully created a RESTful API using Node.js and MongoDB to fetch all items from a database.