MERN

⌘K
  1. Home
  2. Docs
  3. MERN
  4. বই লোন দেয়ার ফিচার যোগ করি

বই লোন দেয়ার ফিচার যোগ করি

আমাদের মডেল ফাইলে লোন স্কিমা যোগ করি এজন্য মডেল ফাইল ওপেন করে নিচের কোড লিখি।

// Define the schema for book loans
const loanSchema = new mongoose.Schema({
    book: { type: mongoose.Schema.Types.ObjectId, ref: 'Book', required: true },
    member: { type: mongoose.Schema.Types.ObjectId, ref: 'Member', required: true },
    issueDate: { type: Date, default: Date.now },
    dueDate: { type: Date, required: true },
    returnDate: { type: Date },
  });
  
const Loan = mongoose.model('Loan', loanSchema );  

module.exports = { Author, Book ,Member,Loan};

routes.js ফাইলটি আপডেট করি

const { Author, Book,Member,Loan } = require('./models');

// Create a new loan
router.post('/loans', async (req, res) => {
    try {
      const { book, member, dueDate } = req.body;
      const newLoan = new Loan({ book, member, dueDate });
      const savedLoan = await newLoan.save();
      res.json(savedLoan);
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: 'Failed to create loan' });
    }
  });
  
  // Get all loans
  router.get('/loans', async (req, res) => {
    try {
      const loans = await Loan.find();
      res.json(loans);
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: 'Failed to retrieve loans' });
    }
  });
  
  // Get a loan by ID
  router.get('/loans/:id', async (req, res) => {
    try {
      const loanId = req.params.id;
      const loan = await Loan.findById(loanId);
  
      if (!loan) {
        return res.status(404).json({ error: 'Loan not found' });
      }
  
      res.json(loan);
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: 'Failed to find loan' });
    }
  });
  
  // Update a loan by ID
  router.put('/loans/:id', async (req, res) => {
    try {
      const loanId = req.params.id;
      const { book, member, dueDate, returnDate } = req.body;
  
      const updatedLoan = await Loan.findByIdAndUpdate(
        loanId,
        { book, member, dueDate, returnDate },
        { new: true }
      );
  
      if (!updatedLoan) {
        return res.status(404).json({ error: 'Loan not found' });
      }
  
      res.json(updatedLoan);
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: 'Failed to update loan' });
    }
  });
  
  // Delete a loan by ID
  router.delete('/loans/:id', async (req, res) => {
    try {
      const loanId = req.params.id;
  
      const deletedLoan = await Loan.findByIdAndDelete(loanId);
  
      if (!deletedLoan) {
        return res.status(404).json({ error: 'Loan not found' });
      }
  
      res.json({ message: 'Loan deleted successfully' });
    } catch (err) {
      console.error(err);
      res.status(500).json({ error: 'Failed to delete loan' });
    }
  });
    

How can we help?