Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

mongodb - Node.js, Mongoose: How to add a product to cart?

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 enter image description here

enter image description here

question from:https://stackoverflow.com/questions/65910094/node-js-mongoose-how-to-add-a-product-to-cart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

check the request header, you should set content-type = application/json and content-lenght = <calculated when request is sent> like the following photo enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...