I am trying to add a product to the user cart and stuck for a while.
My problem is that, when I try to test it via Postman, it throws 400 error from catch and another error in console
Error: Product undefined not found
[TypeScript] at /home/src/services/User.ts:22:11
[TypeScript] at Generator.next (<anonymous>)
[TypeScript] at fulfilled (/home/src/services/User.ts:5:58)
In Services/AddToCart function I obtain product by id via Mongoose findById method
const product = await Product.findById(productId).exec()
if (!product) {
throw new Error(`Product ${productId} not found`)
}
And error comes from here.
Also I have tried with PUT method, but didn't work either.
And to be honest I am not quite sure if this the correct approach. Maybe I need to have cart in Product model.
Any help will be appreciated.
Here is the code:
User model:
import mongoose, { Document, Schema } from 'mongoose'
import Product, { ProductDocument } from './Product'
export type cart = {
product: string
quantity: number
}
export type UserDocument = Document & {
email: string
password: string
cart: cart[]
}
const UserSchema = new mongoose.Schema({
email: {
type: String,
},
password: {
type: String,
},
cart: [
{
product: {
type: Schema.Types.ObjectId,
ref: 'Product',
},
quantity: Number,
},
],
})
export default mongoose.model<UserDocument>('User', UserSchema)
Services:
const addProductToCart = async (
userId: string,
productId: string
): Promise<UserDocument> => {
const user = await User.findById(userId).select('-password').exec()
if (!user) {
throw new Error(`User ${userId} not found`)
}
const product = await Product.findById(productId).exec()
if (!product) {
throw new Error(`Product ${productId} not found`)
}
const itemAdded = user.cart.find((item) => item.product == productId)
if (itemAdded) {
const itemAddedIndex = user.cart.find(
(item) => item.product === product._id
)
itemAdded.quantity += 1
user.cart[itemAddedIndex] = itemAdded
}
if (!itemAdded) {
user.cart.push({ product: productId/* , quantity: 1 */})
}
return user.save()
}
export default{createNewUser, getAllUsers, addProductToCart}
Controllers:
//Patch/inCart/:userid//
export const addProductToCart = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { productId } = req.body
const userId = req.params.userId
const updatedUser = await UserService.addProductToCart(userId, productId)
res.json(updatedUser)
} catch (error) {
console.log(error)
next(new BadRequestError('Something went wrong', error))
}
}
Routers:
import express from 'express'
import {createUser, getUsers, addProductToCart} from '../controllers/User'
const router = express.Router()
router.post('/', createUser)
router.get('/', getUsers)
router.patch('/inCart/:userId', addProductToCart)
export default router
Assuming that I do something wrong while testing, see screenshots from Postman testing
question from:
https://stackoverflow.com/questions/65910094/node-js-mongoose-how-to-add-a-product-to-cart