inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

따라하며 배우는 노드, 리액트 시리즈 - 쇼핑몰 사이트 만들기[전체 리뉴얼]

삭제 하니까 Product.find(...).populdate is not a function 라고 뜹니다 ㅠ

134

껌거슨

작성한 질문수 2

0

] events.js:292

[0]       throw er; // Unhandled 'error' event

[0]       ^

[0]

[0] TypeError: Product.find(...).populdate is not a function

[0]     at D:\공부\React\New_Boilerplate-master\server\routes\users.js:140:18

[0]     at D:\공부\React\New_Boilerplate-master\node_modules\mongoose\lib\model.js:4824:16

[0]     at D:\공부\React\New_Boilerplate-master\node_modules\mongoose\lib\model.js:4824:16

[0]     at D:\공부\React\New_Boilerplate-master\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16

[0]     at D:\공부\React\New_Boilerplate-master\node_modules\mongoose\lib\model.js:4847:21

[0]     at D:\공부\React\New_Boilerplate-master\node_modules\mongoose\lib\query.js:4390:11

[0]     at D:\공부\React\New_Boilerplate-master\node_modules\kareem\index.js:135:16

[0]     at processTicksAndRejections (internal/process/task_queues.js:75:11)

[0] Emitted 'error' event on Function instance at:

[0]     at D:\공부\React\New_Boilerplate-master\node_modules\mongoose\lib\model.js:4826:13

[0]     at D:\공부\React\New_Boilerplate-master\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16

[0]     [... lines matching original stack trace ...]

[0]     at processTicksAndRejections (internal/process/task_queues.js:75:11)

[1] [HPM] Error occurred while trying to proxy request /api/users/removeFromCart?id=600bce9df829516a84314444 from localhost:3000 to http://localhost:5000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)

const express = require('express');
const router = express.Router();
const { User } = require("../models/User");
const { Product } = require("../models/Product");
const { auth } = require("../middleware/auth");

//=================================
//             User
//=================================

router.get("/auth"auth, (reqres=> {
    res.status(200).json({
        _id: req.user._id,
        isAdmin: req.user.role === 0 ? false : true,
        isAuth: true,
        email: req.user.email,
        name: req.user.name,
        lastname: req.user.lastname,
        role: req.user.role,
        image: req.user.image,
        cart: req.user.cart,
        history: req.user.history,
    });
});

router.post("/register", (reqres=> {

    const user = new User(req.body);

    user.save((errdoc=> {
        if (errreturn res.json({ success: falseerr });
        return res.status(200).json({
            success: true
        });
    });
});

router.post("/login", (reqres=> {
    User.findOne({ email: req.body.email }, (erruser=> {
        if (!user)
            return res.json({
                loginSuccess: false,
                message: "Auth failed, email not found"
            });

        user.comparePassword(req.body.password, (errisMatch=> {
            if (!isMatch)
                return res.json({ loginSuccess: falsemessage: "Wrong password" });

            user.generateToken((erruser=> {
                if (errreturn res.status(400).send(err);
                res.cookie("w_authExp"user.tokenExp);
                res
                    .cookie("w_auth"user.token)
                    .status(200)
                    .json({
                        loginSuccess: trueuserId: user._id
                    });
            });
        });
    });
});

router.get("/logout"auth, (reqres=> {
    User.findOneAndUpdate({ _id: req.user._id }, { token: ""tokenExp: "" }, (errdoc=> {
        if (errreturn res.json({ success: falseerr });
        return res.status(200).send({
            success: true
        });
    });
});

router.post("/addToCart"auth, (reqres=> {
    // 먼저 User Collection에 해당 유저의 정보를 가져오기

    User.findOne({ _id: req.user._id},
        (erruserInfo=> {

            // 가져온 정보에서 카트에다 넣으려 하는 상품이 이미 들어 있는지 확인
            let duplicate = false;
            userInfo.cart.forEach((item=> {
                if(item.id === req.body.productId) {
                    duplicate = true;
                }
            })    

            if(duplicate) {
                
                User.findOneAndUpdate(
                    { _id: req.user._id"cart.id": req.body.productId }, 
                    { $inc: {"cart.$.quantity": 1} }, 
                    { new: true }, 
                    (erruserInfo=> {
                        if(errreturn res.status(400).json({ success: falseerr })
                        res.status(200).send(userInfo.cart)
                    }
                )
            } else {
                User.findOneAndUpdate(
                    { _id: req.user._id },
                    { 
                        $push: {
                            cart: {
                                id: req.body.productId,
                                quantity: 1,
                                date: Date.now()
                            }
                        }
                    },
                    { new: true },
                    (erruserInfo=> {
                        if(errreturn res.status(400).json({ success: falseerr })
                        res.status(200).send(userInfo.cart)
                    }
                )
            }

        })
});

router.get('/removeFromCart'auth, (reqres=> {
    // 먼저 카트 안에 내가 지우려고 한 상품을 지워주기
    User.findOneAndUpdate(
        {_id: req.user._id},
        {
            "$pull":
                { "cart": {"id": req.query.id} }
        },
        { new: true },
        (err,userInfo=> {
            let cart = userInfo.cart;
            let array = cart.map(item => {
                return item.id
            })


            // product collection에서 현재 남아 있는 상품들의 정보를 가져오기

            Product.find({ _id: { $in: array } })
                .populdate('writer')
                .exec((errproductInfo=> {
                    return res.status(200).json({
                        productInfo,
                        cart
                    })
                })
        }
    )


})

module.exports = router;

에러 전문입니다 살려주세요

웹앱 mongodb react redux nodejs

답변 1

0

John Ahn

안녕하세요 껌거슨님   

보니깐populdate

이라고 작성하셨는데   populate   으로 바꿔주시면 됩니다 ~ ! 

강의 내용은 훌륭하나, 환경 설정 오류 때문에 진도를 나갈 수 없습니다. 20년 버전 강의.

0

60

1

강의자료는 어디서 볼 수있나요??

0

66

1

이 쇼핑몰 만들기 강의는 관리자페이지 만드는건 없나요

0

113

2

웹에서 실시간 코드반영이 안돼요

0

120

1

app.use질문

0

64

1

강사님께 어떻게 직접질문할수있어요??

0

75

1

const함수같은거 기초강의는 어디있나요

0

81

2

리덕스 참조챕터가 어딨어요? 미리듣고오라는데요

0

81

2

강의가완전 오래되서 다 틀리네 app.jsx도 tailwind css 다틀림 무책임함

0

68

1

개발자도구에 redux란이 없어요

0

88

1

npx tailwindcss init -p 에서 계속 에러나요

0

92

1

쇼핑몰기능중 찜하기 기능은 어떻게 구현하나요

0

138

2

강의하다 줌으로 설명가능한지좀 정확히 알려주세요. 이 선생님 정책이 어떻게 되는데요. 직접 연락할 메일이라도 알려주세요

0

43

1

도표 강의 자료 열람 불가능

0

109

1

tailwindcss를 vite에서 이용하는 방식이 바뀐것 같습니다.

0

1130

2

eslint 설정 후 오류가 납니다.

0

221

1

오버로드 오류

0

149

1

VSCode에서 save를 할 때, landingpage의 useEffect가 실행되는 문제에 대하여

0

169

1

dispatch(logoutUser()) 실행시 dispatch(authuser())도 함께 실행되는 문제

0

228

2

logout할 때, server로 요청을 보내서 authUser middleware를 통과하도록 하는 이유?

0

195

1

webkit-text-size-adjust 오류

0

314

1

does not provide an export named 'userReducer'

0

216

2

빌드 배포

0

140

1

삭제 예정 강의는 언제 삭제 되나요? 저것때문에 수강완료를 못하면 회사에서 비용을 청구한다고 합니다~

0

220

2