cart.controller.js 1.96 KB
Newer Older
1
2
import Cart from "../schemas/Cart.js";

Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
3
const addcart = async (req, res) => {
4
5
    // console.log(req.body)
    const { userId, products} = req.body
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
6
    try {
7
8
9
10
11
12
13
        const cart = await Cart.findOne({ userId: userId })
        console.log(cart)
        // const newProduct = { products: products }
        // const newProduct = {...newProduct}
        // console.log(newProduct)
        console.log(products)
        await Cart.updateOne(
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
14
            { _id: cart._id },
15
16
            // { $addToSet: { products: newProduct } }
            {$set: {products: products}}
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
17
        )
18
19
        res.status(200).send('Cart updated')

20
21
22
23
    } catch (error) {
        console.log(error)
        res.status(500).send('죄송합니다. 다시 입력해 주십시오.')
    }
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
24
25
26
27
}

const showcart = async (req, res) => {
    // const {userId} = req.body
28
29
30
    // console.log(req.cart)
    // console.log(req.id)

Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
31
    try {
32
33
        const cart = await Cart.findOne({ userId: req.id }).populate({
            path: 'products.productId',
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
34
35
36
37
38
39
40
            model: 'Product'
        })
        res.status(200).json(cart.products)
    } catch (error) {
        console.log(error)
        res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
    }
41
42
}

Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const deletecart = async (req, res) => {
    console.log(req.body)
    const { cartId } = req.body
    try {
        await Cart.remove({ _id: cartId })
        res.send("삭제완료")
        // res.json()
    } catch (error) {
        console.log(error)
        res.status(500).send('해당 카트를 삭제하지 못했습니다.')

    }
}
const userById = async (req, res, next, id) => {
    try {
        const cart = await Cart.findOne({ userId: id })
        if (!cart) {
            res.status(404).send("사용자를 찾을 수 없습니다.")
        }
        req.cart = cart
63
        req.id = id
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
64
65
66
67
68
69
70
71
        next()
    } catch (error) {
        res.status(500).send("사용자 아이디 검색 실패")
    }
}


export default { addcart, showcart, deletecart, userById }