order.controller.js 3.01 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
import Order from "../schemas/Order.js";
2
import User from "../schemas/User.js";
Jiwon Yoon's avatar
Jiwon Yoon committed
3
4
import mongoose from 'mongoose'
import Product from "../schemas/Product.js";
Jiwon Yoon's avatar
Jiwon Yoon committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18

const addorder = async (req, res) => {
    const { userId, products, receiverInfo, total } = req.body
    try {
        const newOrder = await new Order({
            userId, products, receiverInfo, total
        }).save()
        res.status(200).send('Order DB에 저장 완료')
    } catch (error) {
        console.log(error)
        res.status(500).send('Order DB에 저장 실패')
    }
}

19
20
21
const Ordered = async (req, res) => {
    const { db } = req.body
    try {
Jiwon Yoon's avatar
Jiwon Yoon committed
22
23
        const ordered = await req.body.findOne({}, { _id: 0 }).select(`${db}`)
        console.log("sub= ", ordered);
24
25
26
27
28
29
        res.json(ordered);
    } catch (error) {
        res.status(500).send('카테고리를 불러오지 못했습니다.')
    }
}

Jiwon Yoon's avatar
Jiwon Yoon committed
30
31
const showorder = async (req, res) => {
    try {
Jiwon Yoon's avatar
Jiwon Yoon committed
32
        const order = await Order.find({ userId: req.userId }).sort({ _id: -1 }).limit(1).populate({
Jiwon Yoon's avatar
Jiwon Yoon committed
33
34
35
            path: 'products.productId',
            model: 'Product'
        })
36
37
        console.log(order)
        res.status(200).json(order[0])
Jiwon Yoon's avatar
Jiwon Yoon committed
38
39
40
41
42
43
44
    } catch (error) {
        console.log(error)
        res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
    }
}


45
46
47
48
49
50
51
52
53
54
55
56
57
const orderById = async (req, res, next, id) => {
    try {
        const user = await User.findById(id)
        if (!user) {
            res.status(404).send('사용자를 찾을 수 없습니다')
        }
        req.userId = user
        next()
    } catch (error) {
        console.log(error);
        res.status(500).send('사용자 아이디 검색 실패')
    }
}
Jiwon Yoon's avatar
Jiwon Yoon committed
58

Jiwon Yoon's avatar
Jiwon Yoon committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const recommendPro = async (req, res) => {
    const productId = req.query.products
    try {
        const recommend = await Order.aggregate([
            {
                $match: {
                    'products.productId': mongoose.Types.ObjectId(productId)
                }
            },
            { "$unwind": "$products" },
            {
                $group: {
                    _id: "$products.productId",
                    count: { $sum: 1 }
                }
            }
        ])
        console.log('recommend=', recommend)
        const filteredRecommend = recommend.filter((el) => String(el._id) !== String(productId))
        console.log('filtering=', filteredRecommend)
        filteredRecommend.sort(function (a, b) {
            if (a.count > b.count) {
                return -1;
            }
            if (a.count < b.count) {
                return 1;
            }
            // a must be equal to b
            return 0;
        });
Jiwon Yoon's avatar
Jiwon Yoon committed
89
90
        const finalrecommend= filteredRecommend.slice(0,4)
        const array = finalrecommend.map(async (el) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
91
92
93
94
95
96
97
98
99
100
101
102
            const aa = await Product.findById(el._id)
            return aa
        })
        const bb  = await Promise.all(array)
        res.json(bb)
    } catch (error) {
        console.log('error in order ', error)
    }
}


export default { addorder, showorder, orderById, Ordered, recommendPro }