500 internal server error, Cast to ObjectId failed for value “undefined” (type string) at path “_id” for model “CAT”

I want to fetch data from server using “id”.. but when I’m doing so i get this error.
Following is my frontend part that is used to get data from server.

“ShowBook” I made this to get data from server using “id”.

import React ,{useEffect,useState} from 'react';
import axios from 'axios';
import {  useParams } from 'react-router-dom';
import BackButton from '../components/BackButton';
import Spinner from '../components/Spinner';



const ShowBook = () => {
  const [books, setBooks] = useState({});
  const [loading, setLoading] = useState(false);
  const { id }  = useParams();
  
  
  
  useEffect(() => {
    setLoading(true);
    axios
    .get(`http://localhost:5555/books/${id}`)
    .then((response) => {
      setBooks(response.data);
      setLoading(false);
    })
    .catch((error) => {
      console.log(error);
      setLoading(false);
    });

  },[])
  
  
  return (
    <div className='p-4'>
      <BackButton/>
      <h1 className='text-3x1 my-4 '>Show Book</h1>
      
      
      {loading ?(
        <Spinner/>
      ):(
        <div className='flex flex-col border-2 border-sky-400 rounded-x1 w-fit p-4'>
          <div className='my-4'>
            <span className='text-x1 mr-4 text-grey-500'>ID</span>
            <span >{books._id}</span>
          </div>
          <div className='my-4'>
            <span className='text-x1 mr-4 text-grey-500'>Title</span>
            <span >{books.title}</span>
          </div>
          <div className='my-4'>
            <span className='text-x1 mr-4 text-grey-500'>Author</span>
            <span >{books.author}</span>
          </div>
          <div className='my-4'>
            <span className='text-x1 mr-4 text-grey-500'>Publish Year</span>
            <span >{books.publishYear}</span>
          </div>

          <div className='my-4'>
            <span className='text-x1 mr-4 text-grey-500'>Create time</span>
            <span >{new Date(books.createdAt).toString()}</span>
          </div>
          <div className='my-4'>
            <span className='text-x1 mr-4 text-grey-500'>Last Updated time </span>
            <span >{new Date(books.updatedAt).toString()}</span>
          </div>


        </div>
      )
}
    
    </div>
  )
}

export default ShowBook 

The following is my backend part (routes ).

import  express  from "express";
import { Book } from "../models/bookModel.js";

const router = express.Router();
//route to save a new book

router.post("/", async (req, res) => {
    try {
      if (!req.body.title || !req.body.author || !req.body.publishYear) {
        return res.status(400).send({
          message: "send all required fields: title, author, publishYear",
        });
      }
  
      const newBook = {
        title: req.body.title,
        author: req.body.author,
        publishYear: req.body.publishYear,
      };
  
      const book = await Book.create(newBook);
      return res.status(201).send(book);
    } catch (error) {
      console.log(error.message);
      res.status(500).send({ message: error.message });
    }
  });
  
  //route to get all books from database
  router.get("/", async (req, res) => {
    try {
      const books = await Book.find({});
      return res.status(200).json({
        count: books.length,
        data: books,
      });
    } catch (error) {
      console.log(error.message);
      res.status(500).send({ message: error.message });
    }
  });
  
  //route to get one book from database by ID
  router.get("/:id", async (req, res) => {
    try {
      const { id } = req.params;
      const book = await Book.findById(id);
      return res.status(200).json(book);
    } catch (error) {
      console.log(error.message);
      res.status(500).send({ message: error.message });
    }
  });
  
  //route to update a book
  router.put("/:id", async (req, res) => {
    try {
      if (!req.body.title || !req.body.author || !req.body.publishYear) {
        return res.status(400).send({
          message: "send all required fields: title, author, publishYear",
        });
      }
      const { id } = req.params;
      const result = await Book.findByIdAndUpdate(id, req.body);
      if (!result) {
        return res.status(404).json({ message: "Book not found" });
      }
      return res.status(200).json({ message: "Book updated successfully" });
    } catch (error) {
      console.log(error.message);
      res.status(500).send({ message: error.message });
    }
  });
  
  //route to delete a book from database by ID
  router.delete("/:id", async (req, res) => {
    try {
      const { id } = req.params;
      const result = await Book.findByIdAndDelete(id, req.body);
      if (!result) {
        return res.status(404).json({ message: "Book not found" });
      }
      return res.status(200).json({ message: "Book deleted successfully" });
    } catch (error) {
      console.log(error.message);
      res.status(500).send({ message: error.message });
    }
  });

  export default router;

This Shows my Schema, i made :-

import mongoose from "mongoose";



const bookSchema = mongoose.Schema(
    {
       title:{
         type: String,
         required:true

       },
       author:{
        type: String,
        required:true

      },
      publishYear:{
        type: Number,
        required:true

      }

    },

    {
        timestamps: true
    },
    
);

export const Book = mongoose.model('CAT', bookSchema);

Following is my APP.js file :-

import React from 'react'
import { Routes , Route} from 'react-router-dom';
import Home from './pages/Home';
import CreateBook from './pages/CreateBook';
import DeleteBook from './pages/DeleteBook';
import EditBook from './pages/EditBook';
import ShowBook from './pages/ShowBook';

const App = () => {
  return (
    <Routes>
      <Route path ='/' element={<Home/>}/>
      <Route path ='/books/create' element={<CreateBook/>}/>
      <Route path ='books/details/:id' element={<ShowBook/>}/>
      <Route path ='books/edit/:id' element={<EditBook/>}/>
      <Route path ='books/delete/:id' element={<DeleteBook/>}/>
    </Routes>
  )
}

export default App

I checked all route, API and endpoints, everything seems fine.
If i use http://localhost:5173/books/details/662c84a93e1918ec47b33047 this i get the data from server.
But if I am passing the {_id} that makes my url like :-http://localhost:5173/books/details/undefined.

The problem what i think is somehow id is not being passed properly.

New contributor

RITIK SINGH is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật