I’m developing an e-commerce application using Express.js, Mongoose, and MongoDB. I’m facing an issue when trying to clear a user’s cart. The goal is to delete all items in the cart for the currently authenticated user. However, I keep encountering the following error message:
Context
- Backend Framework: Node.js with Express
- Database: MongoDB with Mongoose ORM
- Authentication: JWT
Problem Description
I have a clearCart
function in my cart controller that is supposed to delete all cart items for the logged-in user. The user ID is extracted from the JWT token using middleware.
Relevant Code
cartController.js
const asyncHandler = require('express-async-handler');
const Cart = require('../models/cartModel');
const mongoose = require('mongoose');
const clearCart = asyncHandler(async (req, res) => {
try {
console.log("User in clearCart controller:", req.user);
if (!req.user) {
res.status(401).json({ message: "Not authorized, user not found" });
return;
}
const userId = mongoose.Types.ObjectId(req.user._id);
console.log("User ID:", userId);
await Cart.deleteMany({ user: userId });
console.log("Cart cleared for user:", userId);
res.status(200).json({ message: 'Cart cleared' });
} catch (error) {
console.error("Error clearing cart:", error);
res.status(500).json({ error: error.message });
}
});
module.exports = { clearCart }; ```
const mongoose = require('mongoose');
const cartSchema = mongoose.Schema(
{
productId: {
type: String,
required: true,
ref: "BookUpload",
},
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User",
},
quantity: {
type: Number,
required: true,
default: 1,
}
},
{
timestamps: true,
}
);
const Cart = mongoose.model("Cart", cartSchema);
module.exports = Cart;