getting Cannot read properties of undefined (reading ‘_id’) error

I am getting this error again and again even trying different methods it is not getting fixed.

error message
{
“success”: false,
“message”: “Cannot read properties of undefined (reading ‘id’)”
}

auth.js

const Errorhandler = require("../utils/errorhandler");
const catchAsyncErrors = require("./catchasyncerror");
const jwt = require("jsonwebtoken");
const User = require("../model/usermodel");

exports.isAuthenticatedUser = catchAsyncErrors(async (req, res, next) => {
  const { token } = req.cookies;

  if (!token) {
    return next(new Errorhandler("Please Login to access this resource", 401));
  }
  try {
    const decodedData = jwt.verify(token, process.env.JWT_SECRET);
    req.user = await User.findById(decodedData.id);

    // Assuming "user_id" is the name of the cookie
    const userId = req.cookies.user_id;
    const name= req.user.name;

    // Set the user ID in req.user._id
    req.user._id = userId;
    req.user.name=name;

    next();
  } catch (error) {
    return next(new Errorhandler("Invalid token. Please login again.", 401));
  }
});

exports.authorizeRoles = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return next(
        new Errorhandler(
          `Role: ${req.user.role} is not allowed to access this resource `,
          403
        )
      );
    }
    next();
  };
};

productcontroller.js

exports.createProductReview = catchasyncerror(async (req, res, next) => {
    const { rating, comment, productId } = req.body;
  
    const review = {
      user: req.user._id,
      name: req.user.name,
      rating: Number(rating),
      comment,
    };
  
    const product = await Product.findById(productId);
  
    const isReviewed = product.reviews.find(
      (rev) => rev.user.toString() === req.user._id.toString()
    );
  
    if (isReviewed) {
      product.reviews.forEach((rev) => {
        if (rev.user.toString() === req.user._id.toString())
          (rev.rating = rating), (rev.comment = comment);
      });
    } else {
      product.reviews.push(review);
      product.numOfReviews = product.reviews.length;
    }
  
    let avg = 0;
  
    product.reviews.forEach((rev) => {
      avg += rev.rating;
    });
  
    product.ratings = avg / product.reviews.length;
  
    await product.save({ validateBeforeSave: false });
  
    res.status(200).json({
      success: true,
    });
  });

productmodel.js

const mongoose=require("mongoose");

const productSchema=new mongoose.Schema({
    name:{
    type:String,
    required:[true,"please enter product name"]
        },
    description:{
        type:String,
        required:[true,"please enter product description"]

    },
    price:{
        type:Number,
        required:[true,"please enter product description"],
        maxLength:[6,"please enter under limit"]
    },
    ratings:{
        type:String,
        default:0
    },
    images:[
     {
        publicId:{
            type:String,
            required:true
        },
        imageurl:{
            type:String,
            required:true
        }
     }
    ],
    category:{
        type:String,
        required:[true,"please enter product category"],
        maxLength:[6,"please enter under limit"]
    },
    productStock:{
        type:Number,
        required:[true,"please enter product stock"],
        maxLength:[3,"please dont exceed product stock under 1000"]
    },
    numberofReviews:{
        type:Number,
        default:0
    },
    reviews:[
        {
            // user: {
            //     type: mongoose.Schema.ObjectId,
            //     ref: "User",
            //     required: true,
            //   },
            name:{
                type:String,
                required:[true,"name should be there"]
            },
            rating:{
                type:Number,
                required:true
            },
            Comment:{
                type:String,
                required:true
            }
        }
    ],
    // user: {
    //     type: mongoose.Schema.ObjectId,
    //     ref: "User",
    //     required: true,
    //   },
    createdAt:{
        type:Date,
        default:Date.now
    }
})
module.exports=mongoose.model("product",productSchema);

Please help me with this issue.

I expected API to run successfully on put request but it is giving error that it is not reading data from cookie.

Even after replacing req.user with req.auth it’s still not working.

  • Can you edit your question and post the entire error message that you are getting?

    – 

  • done @Abra please help

    – 

Leave a Comment