GET Request

Now lets receive the book we just created.

Javascript




// Get all books
app.get('/books', async (req, res) => {
    try {
        const books = await Book.find();
        res.json(books);
    } catch (error) {
        res.status(500)
            .json({ error: error.message });
    }
});


Send a GET request via postman. You can change the body data if you want.

Head over to MongoDB website and you will see all the data being stored in our database.

How to Build a RESTful API Using Node, Express, and MongoDB ?

This article guides developers through the process of creating a RESTful API using Node.js, Express.js, and MongoDB. It covers setting up the environment, defining routes, implementing CRUD operations, and integrating with MongoDB for data storage, providing a comprehensive introduction to building scalable and efficient APIs.

Similar Reads

Prerequisites:

NodeJS & NPM Express JS MongoDB...

What is a RESTful API?

REST, short for Representational State Transfer, defines an architectural style for constructing web services that utilize HTTP requests to interact with and manipulate data. It serves as a standardized method enabling disparate computer systems to communicate seamlessly over the internet....

Create a New Book (POST):

Javascript app.get('/', (req, res) => {     res.send('Welcome to the Books API!'); });   // Create a new book app.post('/books', async (req, res) => {     res.send('Created a new book'); });   // Get all books app.get('/books', async (req, res) => {     res.send('Received all books'); });   // Get a specific book by ID app.get('/books/:id', async (req, res) => {     res.send('Got a book by ID') });   // Update a book by ID app.put('/books/:id', async (req, res) => {     res.send('Updated book by ID'); });   // Delete a book by ID app.delete('/books/:id', async (req, res) => {     res.send('Deleted book') });...

Create Mongoose Model:

...

POST Request:

Javascript const mongoose = require('mongoose');   const bookSchema = new mongoose.Schema({     title: {         type: String,         required: true     },     author: {         type: String   required: true     }, });   const Book = mongoose.model('Book', bookSchema);   module.exports = Book;...

GET Request:

...

Update a Book By ID (PUT):

Let’s create book using the Book model (POST)...

Delete a Book By ID (DELETE):

...