Skip to content
Snippets Groups Projects
Select Git revision
  • 21fcb188ee195f1cb446ac0fe1ed3cc69462ed50
  • master default protected
2 results

book.js

Blame
  • book.js 1.43 KiB
    const router = require('express').Router();
    let Book = require('../model/book.model');
    
    router.route('/').get((req, res) => {
      Book.find()
        .then(books => res.json(books))
        .catch(err => res.status(400).json('Error: ' + err));
    });
    
    router.route('/add').post((req, res) => {
      const book_id = req.body.book_id;
      const book_name = req.body.book_name;
      const author = req.body.author;
      const price = Number(req.body.price);
    
      const newBook = new Book({_id: book_id,book_name,author,price});
    
      newBook.save()
        .then(() => res.json('Book added!'))
        .catch(err => res.status(400).json('Error: ' + err));
    });
    
    router.route('/:id').get((req, res) => {
      Book.findById(req.params.id)
        .then(books => res.json(books))
        .catch(err => res.status(400).json('Error: ' + err));
    });
    
    router.route('/:id').delete((req, res) => {
      Book.findByIdAndDelete(req.params.id)
        .then(() => res.json('Book deleted.'))
        .catch(err => res.status(400).json('Error: ' + err));
    });
    
    router.route('/update/:id').post((req, res) => {
      Book.findById(req.params.id)
        .then(book => {
          book.book_id = req.body.book_id;
          book.book_name = req.body.book_name;
          book.author = req.body.author;
          book.price = Number(req.body.price);
    
          book.save()
            .then(() => res.json('Book updated!'))
            .catch(err => res.status(400).json('Error: ' + err));
        })
        .catch(err => res.status(400).json('Error: ' + err));
    });
    
    module.exports = router;