Delete a Book By ID (DELETE)
To delete a specific book, you send a request to the API with the book’s unique ID. The API then identifies the book with that ID in the database and removes it.
Javascript
// Delete a book by ID app. delete ( '/books/:id' , async (req, res) => { try { const book = await Book.findByIdAndDelete(req.params.id); if (!book) { return res.status(404) .json({ error: 'Book not found' }); } res.json({ message: 'Book deleted successfully' }); } catch (error) { res.status(500) .json({ error: error.message }); } }); |
Example: Below is the Complete Example of MongoDB CRUD operations we have discussed above:
Javascript
require( 'dotenv' ).config(); const express = require( 'express' ); const mongoose = require( 'mongoose' ); const Book = require( './models/book' ); const app = express(); const URI = process.env.MONGODB_URI mongoose.connect(URI) const database = mongoose.connection database.on( 'err' , (err) => { console.log(err) }) database.once( 'connected' , () => { console.log( 'Database Connected to the server' ); }) app.use(express.json()) app.get( '/' , (req, res) => { res.send( 'Welcome to the Books API!' ); }); // Create a new book app.post( '/books' , async (req, res) => { try { const book = new Book(req.body); await book.save(); res.status(201).json(book); } catch (error) { res.status(400) .json({ error: error.message }); } }); // 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 } ); } }); // Update a book by ID app.put( '/books/:id' , async (req, res) => { try { const book = await Book.findByIdAndUpdate( req.params.id, req.body, { new : true } ); if (!book) { return res.status(404) .json({ error: 'Book not found' }); } res.json(book); } catch (error) { res.status(500).json({ error: error.message }); } }); // Delete a book by ID app. delete ( '/books/:id' , async (req, res) => { try { const book = await Book.findByIdAndDelete(req.params.id); if (!book) { return res.status(404) .json({ error: 'Book not found' }); } res.json({ message: 'Book deleted successfully' }); } catch (error) { res.status(500) .json({ error: error.message }); } }); app.listen(3000, (req, res) => { console.log( 'Server is listening on port 3000' ); }); |
Here, you have the comprehensive code for implementing a fully functional RESTful API. This code covers all aspects of CRUD operations, allowing you to effortlessly manage your book data. Feel free to modify and build upon it!
Output:
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.