'TypeError: Cannot read properties of undefined (reading 'toString') in react
I am working on the MERN stack project. here I have one endPoint for users, user can update their details
router.put('/updateuser/:id',fetchuser, async (req, res) => {
const {name, email, role, password} = req.body;
//create new user object
const newUser = {};
if(name){newUser.name = name};
if(email){newUser.email = email};
if(password){newUser.password = password};
if(role){newUser.role = role};role
//Find the user will be updated and update it
let user = await User.findById(req.params.id);
if(!user){return res.status(404).send("note found")}
if(user.user.toString() !== req.user.id){
return res.status(401).send("Not Allowed");
}
user = await User.findByIdAndUpdate(req.params.id, {$set: newUser},{ new:true})
res.json({user});
})
endpoint not working showing error TypeError: Cannot read properties of undefined (reading 'toString')
you can see the below image

if anyone knows how to fix this Typos error please let me know
Update:
see the image to better understand

I think errors occur because I am using the Same name for user declare and My user model. but after changing name error not resolved
Solution 1:[1]
The error here is trying to say that it cannot read the property 'toString' from the 'user' property, as the 'user' property is not defined or does not exists.
In your case it means that user.user is undefined, hence the compiler is not able to read 'toString' property. Maybe you meant to try something like:
if(user.toString() !== req.user.id)
Although I think you should first debug and check the value of 'user' returned by User.findById before checking for the condition and seeing what exactly is returned
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manul Aggarwal |
