cart.controller.js 1.84 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
    const { userId, products} = req.body
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
5
    try {
6
7
        const cart = await Cart.findOne({ userId: userId })
        await Cart.updateOne(
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
8
            { _id: cart._id },
Jiwon Yoon's avatar
Jiwon Yoon committed
9
            {$push: {products: products}}
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
10
        )
Jiwon Yoon's avatar
0113    
Jiwon Yoon committed
11
        res.status(200).send('카트에 저장되었습니다.')
12
13
    } catch (error) {
        console.log(error)
Jiwon Yoon's avatar
0113    
Jiwon Yoon committed
14
        res.status(500).send('카트에 저장할 수 없습니다.')
15
    }
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
16
17
18
19
}

const showcart = async (req, res) => {
    try {
20
21
        const cart = await Cart.findOne({ userId: req.id }).populate({
            path: 'products.productId',
Jiwon Yoon's avatar
Jiwon Yoon committed
22
            model: 'Product' 
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
23
24
25
26
27
28
        })
        res.status(200).json(cart.products)
    } catch (error) {
        console.log(error)
        res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
    }
29
30
}

Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
31
32
const deletecart = async (req, res) => {
    console.log(req.body)
Jiwon Yoon's avatar
Jiwon Yoon committed
33
    const { userId,cartId } = req.body
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
34
    try {
Jiwon Yoon's avatar
Jiwon Yoon committed
35
36
37
38
39
40
41
42
43
44
        const cart = await Cart.findOneAndUpdate(
            { userId: userId },
            { $pull: { products: {_id:cartId} } },
            { new: true }
          ).populate({
            path: 'products.productId',
            model: 'Product'
          })
        // res.send("삭제완료")
        res.json(cart)
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
45
46
47
48
49
50
51
52
53
54
55
56
57
    } 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
58
        req.id = id
Jiwon Yoon's avatar
qwr    
Jiwon Yoon committed
59
60
61
62
63
64
65
66
        next()
    } catch (error) {
        res.status(500).send("사용자 아이디 검색 실패")
    }
}


export default { addcart, showcart, deletecart, userById }