Click here to Skip to main content
15,503,491 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
He guys, please I need some help with my NextJS/NodeJS project. I'm having the error:
TypeError: Cannot read property '_id' of undefined
    at currentInstructor (C:\Users\Sammy\Desktop\eLearn\server\controllers\instructor.js:57:30


I can't seem to identify where the error is actually coming from. Please guys, maybe I'm missing something, just need some help to fetch it out.

What I have tried:

Below is my Controllers Instructor code:

import { LexRuntime } from 'aws-sdk';
import { v4 as uuidv4 } from 'uuid';
import User from '../models/user';


export const currentInstructor = async (res, req) => {
  try {
    //  1. Find user from db
    let user = await User.findById(req.user._id).select('-password').exec();

    if (!user.role.includes('Instructor')) {
      return res.sendStatus(403);
    } else {
      res.json({ ok: true });
    }
  } catch (err) {
    console.log(err);
  }
};


Below is my route Instructor code:

import express from 'express';
const router = express.Router();
// Import Middleware
import { requireSignin, requireAuth } from '../middlewares';
// Import Controllers
import { currentInstructor } from '../controllers/instructor';

router.get('/current-instructor', requireSignin, currentInstructor);

module.exports = router;


Below is my InstructorRoute code:
import { useEffect, useState } from 'react';
import axios from 'axios';
import { useRouter } from 'next/router';
import { SyncOutlined } from '@ant-design/icons';
import UserNav from '../nav/UserNav';

const InstructorRoute = ({ children }) => {
  // State
  const [ok, setOk] = useState(false);

  //   Router
  const router = useRouter();

  useEffect(() => {
    fetchInstructor();
  }, []);

  const fetchInstructor = async () => {
    try {
      const { data } = await axios.get('/api/current-instructor');
      console.log(data);
      if (data.ok) setOk(true);
    } catch (err) {
      console.log(err);
      setOk(false);
      router.push('/');
    }
  };

  return (
    <>
      {!ok ? (
        <SyncOutlined
          spin
          className='d-flex justify-content-center display-1 text-primary p-5'
        />
      ) : (
        <div className='container-fluid'>
          <div className='row'>
            <div className='col-md-2'>
              <UserNav />
            </div>
            <div className='col-md-10'>{children}</div>
          </div>
        </div>
      )}
    </>
  );
};

export default InstructorRoute;


Then I tried to navigate to the create course page which is below:

import axios from 'axios';
import InstructorRoute from '../../../components/routes/InstructorRoute';

const CourseCreate = () => {
  return (
    <InstructorRoute>
      <h1 className='jumbotron text-center square'>Create Course</h1>
    </InstructorRoute>
  );
};

export default CourseCreate;


EACH TIME I TRY TO NAVIGATE TO THE CREATE COURSE PAGE, I GET THE ERROR SAYING:
TypeError: Cannot read property '_id' of undefined
    at currentInstructor (C:\Users\Sammy\Desktop\eLearn\server\controllers\instructor.js:57:30
Posted
Comments
Richard MacCutchan 19-Nov-21 3:58am    
The error message tells you where it is coming from: C:\Users\Sammy\Desktop\eLearn\server\controllers\instructor.js:57:30 - character position 30 of line 57. But since you have not explained which is line 57 it is difficult to know which reference is undefined.
Amogs 19-Nov-21 4:08am    
Thank you, What is in line 57 is this code below (from Controllers Instructor code, above) and that's what it is throwing as error:

// 1. Find user from db
let user = await User.findById(req.user._id).select('-password').exec();

And it is the "_id" from findById(req.user._id) that is throwing the error. I can't seem to understand why the error cos I had used it in another scenario to update database and no error was thrown. It successfully found the user by ID and updated it.
So I really can't get why this one is throwing an error.
Richard MacCutchan 19-Nov-21 4:50am    
The problem is, as noted in the error message, that it is trying to access the _id property of an undefined reference. So you need to find out which of req or user is not defined, and why.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900