skip to Main Content

Issue:

I’m working on a React application with a backend built using Express and MongoDB. I’m encountering issues when trying to fetch student profile data. The browser console shows a 500 Internal Server Error.

Backend Setup:

  • Backend: Express, MongoDB

  • Relevant Code Snippets:

    • studentModel.js:
    • const mongoose = require("mongoose");
      
      const studentSchema = new mongoose.Schema({
        userId: mongoose.Schema.Types.ObjectId, // Reference to the User model
        personalDetails: {
          name: String,
          email: String,
          registerNumber: String,
          department: String,
          college: String,
          program: String,
          specialization: String,
          education: String,
          section: String,
        },
        professionalDetails: {
          skills: String,
          areaOfInterest: String,
          languages: [String],
        },
        documents: {
          photo: String, // Storing file paths or URLs
          resume: String,
          cv: String,
        },
      });
      
      const Student = mongoose.model("Student", studentSchema);
      module.exports = Student;
      
      

studentController.js:

exports.getStudent = async (req, res) => {
  try {
    const student = await Student.findById(req.params.id);
    if (!student) {
      return res.status(404).send();
    }
    res.send(student);
  } catch (error) {
    res.status(500).send();
  }
};

Frontend Setup:

  • Frontend: React

  • Relevant Code Snippets:

    • ProfilePage.js:
import React, { useEffect, useState } from "react";
import StudentHeader from "../Header/StudentHeader";
import Footer from "../Footer/Footer";
import "../../styles/ApplyForInterview.css";

const ProfilePage = () => {
  const [studentData, setStudentData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchStudentData = async () => {
      try {
        const token = localStorage.getItem("token");
        if (!token) {
          throw new Error("Authentication required");
        }

        const response = await fetch("/api/v1/students/profile", {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
        });

        if (!response.ok) {
          throw new Error(`Error ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        setStudentData(data);
      } catch (error) {
        setError(error.message);
      }
    };

    fetchStudentData();
  }, []);

  if (error) {
    return <div>Error: {error}</div>;
  }

  if (!studentData) {
    return <div>Loading...</div>;
  }

  const { personalDetails, professionalDetails, documents } = studentData;

  return (
    <div className="growwithguru-container">
      <StudentHeader />
      <div className="form-container">
        <h1>Welcome to GROW WITH GURU - Your Path to Interview Success</h1>
        <div className="form-box profile-section">
          <div className="profile-photo-placeholder">
            {documents?.photo ? (
              <img src={documents.photo} alt="Student" />
            ) : (
              <div>No Photo Available</div>
            )}
          </div>
          <div className="profile-info-section">
            {/* Personal Details */}
            <div className="profile-info-group">
              <label className="profile-label">Name:</label>
              <div className="profile-value">
                {personalDetails?.name || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Email ID:</label>
              <div className="profile-value">
                {personalDetails?.email || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Register No:</label>
              <div className="profile-value">
                {personalDetails?.registerNumber || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Department:</label>
              <div className="profile-value">
                {personalDetails?.department || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">College:</label>
              <div className="profile-value">
                {personalDetails?.college || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Program:</label>
              <div className="profile-value">
                {personalDetails?.program || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Specialization:</label>
              <div className="profile-value">
                {personalDetails?.specialization || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Education:</label>
              <div className="profile-value">
                {personalDetails?.education || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Section:</label>
              <div className="profile-value">
                {personalDetails?.section || "N/A"}
              </div>
            </div>
            {/* Professional Details */}
            <div className="profile-info-group">
              <label className="profile-label">Skills:</label>
              <div className="profile-value">
                {professionalDetails?.skills || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Area of Interest:</label>
              <div className="profile-value">
                {professionalDetails?.areaOfInterest || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Languages:</label>
              <div className="profile-value">
                {professionalDetails?.languages?.join(", ") || "N/A"}
              </div>
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default ProfilePage;

Error Details:

The error occurs when I attempt to access the profile page. The console logs show:

GET http://localhost:3000/api/v1/students/profile 500 (Internal Server Error)

here is my github link for the project do help me:https://github.com/vamshigadde09/GROW-WITH-GURU

What I’ve Tried:

  • Verified that MongoDB is running and accessible.

  • Checked the routes and controllers to ensure they are correctly defined.

  • Confirmed that the token is present and correctly used in the request.

Additional Information:

  • Backend server log: No specific error message, just a 500 status code.

  • Frontend framework: React

  • Backend framework: Express

2

Answers


  1. Add a log to the catch section. This will log any errors to the console, which can help in diagnosing the issue.

    } catch (error) {
      console.error("Error fetching student:", error); // Log the error
      res.status(500).send();
    }
    
    Login or Signup to reply.
  2. Before we start, please note that the error handler at present obscures the error object as commented by the community members. This needs to be corrected as it has been guided by them.

    Now let us move on to this post.

    The code below may be an MRE – minimal reproducible example, of this case. It throws a cast error which is most likely to occur in the given code. The subsequent paragraph below explains the reason for the cast error. Please use this MRE and the reasoning, to match with your case to spot and fix the issues. If there is anything mismatches with this MRE, please comment, shall work together to resolve it.

    An MRE throws a cast error

    server.js

    const express = require('express');
    const mongoose = require('mongoose');
    let TestModel;
    const app = express();
    
    mongoose.connect('mongodb://127.0.0.1:27017/test').then((res) => {
     const testSchema = new mongoose.Schema({ key1: Number });
     TestModel = mongoose.model('TestModel', testSchema);
     fetch('http://localhost:3000/api/v1/students/profile');
    });
    
    app.get('/api/v1/students/:id', async (req, res, next) => {
     try {
       const id = req.params.id;
       console.log(await TestModel.findById(id));
     } catch (error) {
       console.log(error);
     }
    });
    
    app.listen(3000, () => console.log('L@3000'));
    

    Test run

    node server.js
    

    server console output

    CastError: Cast to ObjectId failed for value "profile" (type string) at path "_id" for model "TestModel"...
    

    Reasons for the error:

    a) The Cast Error thrown here is from the Mongoose system. Mongoose will automatically try to cast the values in an expression to the respective data types in schema definition. In this case, it tries to convert the string value ‘profile’ into the data type of _id key. As we know _id key is an automatically created one by the MongoDB system. By default, it is of the type – ObjectId. Therefore the Mongoose system tried to convert the string value ‘profile’ to the type ObjectId, and it failed and threw the reported error. One of the instances of a valid string value which can be successfully converted into ObjectId would be something like "5e1a0651741b255ddda996c4" which is a 24-character hexadecimal string.

    b) Now the reason for this unexpected value ‘profile’ is due to the possible missing or mismatch between the request URL and the route path used here.

    request URL : /api/v1/students/profile
    route path : /api/v1/students/:id
    

    The route parameter id in the route path incorrectly captures the string ‘profile’ in the request URL. Therefore the value id erroneously becomes ‘profile’. This should be the root cause for the cast error.

    Solution:

    a) Correct the route path to /api/v1/students/profile/:id

    b) Pass a valid string value for the route parameter id, as shown below

     const _id = "5e1a0651741b255ddda996c4"
     fetch('http://localhost:3000/api/v1/students/profile/'+_id);
    

    An MRE fixes a possible cast error

    const express = require('express');
    const mongoose = require('mongoose');
    let TestModel;
    const app = express();
    
    
    mongoose.connect('mongodb://127.0.0.1:27017/test').then((res) => {
     const testSchema = new mongoose.Schema({ key1: Number });
     TestModel = mongoose.model('TestModel', testSchema);
     const _id = '5e1a0651741b255ddda996c4';
     fetch('http://localhost:3000/api/v1/students/profile/' + _id);
    });
    
    
    app.get('/api/v1/students/profile/:id', async (req, res, next) => {
     try {
       const id = req.params.id;
       await TestModel.findById(id);
       console.log('done');
       res.send('done');
     } catch (error) {
       console.log(error);
       res.send(error);
     }
    });
    
    app.listen(3000, () => console.log('L@3000'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search