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 {
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 { requireSignin, requireAuth } from '../middlewares';
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 }) => {
const [ok, setOk] = useState(false);
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