Hi Mosh,
Got an error while getting the current user using GET method in postman. Here’s the error
NodeJs/vidly/routes/users.js:10
const user = await User.findById(req.user._id).select(‘-password’);
^
TypeError: Cannot read properties of undefined (reading ‘_id’)
const mongoose = require(‘mongoose’);
const express = require(‘express’);
const router = express.Router();
const _ = require(‘lodash’);
const bcrypt = require(‘bcrypt’);
const auth = require(‘…/middleware/auth’);
const { User, validate } = require(‘…/models/user’);
router.get(‘/me’, auth, async (req, res) => {
const user = await User.findById(req.user._id).select(‘-password’);
res.send(user);
});
I’m able to fixed the problem using res.user._id instead of req.user._id. Im still confused because the middleware authorization return a res.user as shown
const jwt = require(‘jsonwebtoken’);
const config = require(‘config’);
module.exports = function (req, res, next) {
const token = req.header(‘x-auth-token’);
if (!token) return res.status(401).send(‘Access denied. No token provided.’);
try {
const decoded = jwt.verify(token, config.get(‘jwtPrivateKey’));
res.user = decoded;
next();
} catch (ex) {
res.status(400).send(‘Invalid token.’);
}
};
Harvel
March 6, 2023, 1:42pm
3
Hey its Harvel,
Actually you set the user object on the response object instead of the request object,
So req.user is undefined
Harvel
March 6, 2023, 1:43pm
4
Set the user object on the request object in the auth middleware
Hi Harvel,
my fault actually when I review that section yesterday. my bad. Thanks anyway.
Dsoeiro
February 8, 2024, 12:40pm
6
Hi, I’m with the exact same problem, I verified and I have the code exactly as you have it there but it stills shows me the error