묻고 답해요
164만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 쇼핑몰 사이트 만들기[전체 리뉴얼]
삭제 하니까 Product.find(...).populdate is not a function 라고 뜹니다 ㅠ
] 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, (req, res) => { 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", (req, res) => { const user = new User(req.body); user.save((err, doc) => { if (err) return res.json({ success: false, err }); return res.status(200).json({ success: true }); }); }); router.post("/login", (req, res) => { User.findOne({ email: req.body.email }, (err, user) => { if (!user) return res.json({ loginSuccess: false, message: "Auth failed, email not found" }); user.comparePassword(req.body.password, (err, isMatch) => { if (!isMatch) return res.json({ loginSuccess: false, message: "Wrong password" }); user.generateToken((err, user) => { if (err) return res.status(400).send(err); res.cookie("w_authExp", user.tokenExp); res .cookie("w_auth", user.token) .status(200) .json({ loginSuccess: true, userId: user._id }); }); }); }); }); router.get("/logout", auth, (req, res) => { User.findOneAndUpdate({ _id: req.user._id }, { token: "", tokenExp: "" }, (err, doc) => { if (err) return res.json({ success: false, err }); return res.status(200).send({ success: true }); }); }); router.post("/addToCart", auth, (req, res) => { // 먼저 User Collection에 해당 유저의 정보를 가져오기 User.findOne({ _id: req.user._id}, (err, userInfo) => { // 가져온 정보에서 카트에다 넣으려 하는 상품이 이미 들어 있는지 확인 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 }, (err, userInfo) => { if(err) return res.status(400).json({ success: false, err }) 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 }, (err, userInfo) => { if(err) return res.status(400).json({ success: false, err }) res.status(200).send(userInfo.cart) } ) } }) }); router.get('/removeFromCart', auth, (req, res) => { // 먼저 카트 안에 내가 지우려고 한 상품을 지워주기 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((err, productInfo) => { return res.status(200).json({ productInfo, cart }) }) } ) }) module.exports = router; 에러 전문입니다 살려주세요
-
미해결Flutter 입문 - 안드로이드, iOS 개발을 한 번에 (with Firebase)
FAILED_PRECONDITION 오류발생
storage 까지는 잘올라가지만 db에는 저장되지 않네요 아래는 안드로이드 오류 로그입니다. api enable은 해두었고, google-service json 파일도 올바른 경로에 올려두었어요 [로그내용] W/Firestore( 9474): (22.0.2) [WriteStream]: (27ee32b) Stream closed with status: Status{code=FAILED_PRECONDITION, description=The Cloud Firestore API is not available for Datastore Mode projects., cause=null}.
-
미해결스프링 부트 개념과 활용
dependency 추가할때 궁금한것이 있습니다
dependency에서 undertow 추가 하실때 보면 자연스럽게 org.springframework.boot gruopId 설정하시고 spring-boot-starter-undertow를 찾으시던데 undertow가 spring-boot-starter 에 존재하는것을 원래 알고 계시기 때문에 그렇게 쓰시는건가요? 그리고 다른 dependency를 추가할때도 spring-boot-starter에 있는지 확인하고 없다면 찾아서 추가해야 하는건가요?
-
해결됨페이스북 클론 - full stack 웹 개발
position: relative
.wrap .list01 { width: 200px; height: 200px; background: hotpink; position: relative; left: 50%; top: 50%; transform: translate(-50%, -50%); } 다른거 다그대로하고, position만 relative로 했더니 똑같이 적용이 됩니다! relative는 기준이 자기 자신인줄 알았는데, 왜 똑같이 될까요 ???
-
미해결실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화
v6의 OrderQueryDto 생성자 호출 부분에서 에러가 발생하는데 이유를 잘몰겠어여
안녕하세요 김영한 강사님v6 로직을 작성하던중 에러가 발생하는데여 v6 로직중에 아래의 코드중 OrderQueryDto 생성자 호출 부분에서 에러가 발생하는데 원인이 무엇일까여? 그리고 v6 최적화 로직은 전체적으로 쉽지 않은데 일단 v6 최적화 부분은 대충 의미를 파악한뒤 다음 강의로 넘어가도 될까여? controller/OrderApiController.java @GetMapping("/api/v6/orders")public List<OrderFlatDto> ordersV6() { List<OrderFlatDto> flats = orderQueryRepository.findAllByDto_flat(); return flats.stream() .collect(groupingBy(o -> new OrderQueryDto(o.getOrderId(), o.getName(), o.getOrderDate(), o.getOrderStatus(), o.getAddress()), mapping(o -> new OrderItemQueryDto(o.getOrderId(), o.getItemName(), o.getOrderPrice(), o.getCount()), toList()))) .entrySet() .stream().map(e -> new OrderQueryDto(e.getKey().getOrderId(), e.getKey().getName(), e.getKey().getOrderDate(), e.getKey().getOrderStatus(), e.getKey().getAddress(), e.getValue())) .collect(toList());} OrderQueryDto.java @Data@EqualsAndHashCode(of = "orderId")public class OrderQueryDto { private Long orderId; private String name; private LocalDateTime orderDate; //주문시간 private OrderStatus orderStatus; private Address address; private List<OrderItemQueryDto> orderItems; public OrderQueryDto(Long orderId, String name, LocalDateTime orderDate, OrderStatus orderStatus, Address address) { this.orderId = orderId; this.name = name; this.orderDate = orderDate; this.orderStatus = orderStatus; this.address = address; }}
-
미해결홍정모의 따라하며 배우는 C언어
대소 비교 연산자 질문 드립니다!
코드를 보지 않고 미리 작성하던 중, 습관적으로 수학과 같이 if ( '0' <= ch <= '9') ch = '*' 와 같이 작성하였을 때 숫자 뿐만 아니라 모든 문자가 *로 바뀌는 것을 확인했습니다. 논리 연산자를 차이가 무엇인가 생각해봤는데... if 문 안의 '0'<=ch 가 먼저 연산이 되고, 이 자체로 expression 이니까 이 식의 value가 1이 되어서, 결국 if ( 1 < '9' ) 가 되어 항상 참이되는 식이 나온 것 같은데 맞나요 ?? 논리 연산자를 사용한 식과 단순히 비교 연산자를 연속해서 쓴 것의 차이가 궁금합니다!
-
해결됨웹 게임을 만들며 배우는 React
useEffect안에서의 배열 질문 있습니다
안녕하세요. 강의보다가 궁금한 점이 생겨서 질문드립니다. 배열에 감지할 state를 여러개 넣을 수 있다고 배웠는데 강의에서처럼 [imgCoord, score] 로 작성하면 둘 다(&&) 바뀌었을 때 실행되는 건가요, 아니면 둘 중 하나만(||) 바뀌어도 실행되는 건가요??
-
미해결[C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part4: 게임 서버
디스어셈블리가 안되어서 질문드립니다.
처음에는 주소가 비어져있고 " 디스어셈블리를 실행 모드에서 표시할수 없습니다" 만 있었습니다. 주소를 직접 입력해보니 , 위 메세지가 나옵니다. 어떻게 해결해야 할까요?
-
미해결공공데이터로 파이썬 데이터 분석 시작하기
상관계수 유의미 검정
선생님~ 상관계수를 시각화 할 때 annot=True 하면 나오는 상관계수 수치가 통계적으로 유의한 계수인지 알 수는 없는건가요..?
-
미해결생활코딩 - React
크롬 웹스토어의 리액트툴 링크입니다.
https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=ko
-
미해결it 취업을 위한 알고리즘 문제풀이 입문 (with C/C++) : 코딩테스트 대비
그래프 내부에 사이클이 생기면 어떻게 조건을 끝내나요?
1->2->3->4 까지 가고 4->5로 가는 간선이 없다고 가정했을때 dfs(4)에서 함수가 끝나지 않을 것 같은데.. 이런 조건은 어떻게 처리해야 하는지 궁금합니다!
-
미해결공공데이터로 파이썬 데이터 분석 시작하기
KDE 그래프 관련
선생님 위도에 대해서 distplot 그리실 때 커널밀도 함수가 그려지는데 그것은 무슨 의미를 하나요? 그리고 수치형데이터에서 어떠한 것을 보고 싶어서 그리는 건가요~? '위도' 말고 다른 예를 들어서 자세한 설명 부탁드리겠습니다.. ㅠ 강의에서는 그래프 그리실 때 간혹..' A그래프는 A이다 '라고만 설명하셔서 수강생 입장으로서는..'이 그래프는 어떨때 사용하는 게 좋은거지? 이 그래프는 왜 그리는거지? ' 라는 의문이 들 때가 있습니다..ㅠ
-
미해결자바스크립트 비기너: 튼튼한 기본 만들기
머릿속이 꼬여서 도움을 청합니다.
안녕하세요. 수강 중 본의아니게 머리가 꼬여 구글링을 열심히 해보았지만 명쾌한 답을 찾지 못하여 이렇게 여쭙게 되었습니다. 질문 1) Function()과 new Function()이 같다고 하셨습니다. 그렇다면 대문자 Function() 문법과 소문자 function()문법의 차이는 파라미터 작성법이 끝인가요?? 용도나 쓰임, 활용의 차이가 따로 있나요?? 질문 2) var f1 = function(){}; var f2 = new f1; console.log(Object.prototype.toString.call(f1)); console.log(Object.prototype.toString.call(f2)); var s1 = String; var s2 = new s1; console.log(Object.prototype.toString.call(s1)); console.log(Object.prototype.toString.call(s2)); ---실행값---- [object Function] [object Object] [object Function] [object String] 이렇게 나오는 걸 확인할 수 있었습니다. 위 단락과 아래 단락이 차이나는 이유를 알 수 있을까요?? 제 생각의 회로는 이러합니다. s2가 s1이라는 오브젝트의 인스턴스이므로 s2도 Object의 오브젝트라고 생각했습니다. 내부적으로 이해 해보고 싶은데 많이 수준이 부족한 것 같아 이렇게 도움을 청합니다.
-
미해결바닥부터 시작하는 STM32 드론 개발의 모든 것
배터리연결
컴파일 시에 배터리 연결없이 st link로만 연결을 하여 컴파일을 해도 코드수행이 되는것 같습니다. 앞으로도 이렇게 진행하여도 괜찮을까요??
-
미해결실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
질문있습니다!
안녕하세요! 강의를 보던 도중 걸리는게 있어서 질문 드립니다. 제가 포트폴리오를 만들어야하는 취준생인데 입문편 마지막 강의에서 활용 1편을 들은 후 JPA를 들어도 괜찮다고 하신 말씀에 활용편을 먼저 구매했는데 JPA에 대한 언급이 많으셔서요. 혹시 JPA편을 듣고 이 강의를 듣는게 맞는걸까요 ?
-
미해결[리뉴얼] 파이썬입문과 크롤링기초 부트캠프 [파이썬, 웹, 데이터 이해 기본까지] (업데이트)
from math import sqrt, factorial 라이브러리 선언
선생님 질문이 있습니다. 질문에 허접할수도 있는데. 조금 이해가 되지 않아서 문의 드립니다. 9분 47초부터 쯤 강의에서 from 을 쓰는 이유는 매번 라이브러리를 math.sqrt <-- 쓰는게 불편해서 위에처럼 from math import sqrt, factorial 요렇게 선언 하는 방법도 있다 하쎳는데 4:17부터 처음 라이브러리 가르키실때 import math num = math.pow(3, 3) print(num) 요렇게 하셨는데 저는 응용을 해보았습니다. 위 사진과 같이 from math import sqrt, factorial 라고 정의 하지 않고 import만 했는데 from을 정의하지 않고 3번째 사진처럼 math.을 생략하고 써도 결과가 나오는 것이 이유가 먼지 모르겠습니다. 제가 너무 초보라서 잘못 이해한것인지.. 알려주시면 감사합니다 ㅠ.ㅠ
-
미해결Vue로 Nodebird SNS 만들기
'Missing credentials' 이 뜹니다.. passport 문제
일단, 1. 프론트로 부터 받아온 req.body 를 찍으니 아래와 같이 잘 넘어 왔구요. 그 다음 아래 app.js info로 넘어온 데이터가 저렇게 missing credentials로 나옵니다. 이전에 다른 수강생분께서 질문주신대로 잘 맞춰서 했다고 생각하는데 어디가 이상이 있는건지 문의 드립니다.. 2. 백엔드 app.js 에서 로그인 받는 부분 입니다. app.post('/user/login', async(req, res, next) => { console.log('/user/login-----> ', req.body); try { // -> passport LocalStrategy 으로 전송. passport.authenticate('local', (err, user, info) =>{ if (err) { console.log('[post]/user/login (Error) ', err); return next(err); } if (info) { console.log('[post]/user/login (Fail) ', info); return res.status(401).send(info); } console.log('[post]/user/login ', user); // 세션에다 사용자 정보 저장( 어떻게 저장할 것인가? ) return req.login(user, async(err) => { if (err) { return next(err); } return res.json(user); }); })(res, req, next); } catch(err) { } }); 3. passport/local.js 코드 입니다. 여기에서도 usernameField랑 passwordField에 저기 1번에서 넘어온 parameter그대로 사용해서 해줬는데요. 왜 자꾸 missing credentails가 뜨는지... 도통 해결을 못하겠네요 ㅜㅜ const passport = require('passport'); const { Strategy: LocalStrategy } = require('passport-local'); const db = require('../models'); const bcrypt = require('bcrypt'); module.exports = () => { passport.use( new LocalStrategy( { usernameField: 'myid', // req.body.myid passwordField: 'password', //req.body.password }, async (myid, password, done) => { try { console.log('******* passport / local ', myid, password); // 사용자 여부 체크 const existUser = await db.User.findOne({ where: { myid } }); if (!exexistUser) { // done(에러, 성공, 실패) return done(null, false, { reason: '존재 하지 않는 사용자 입니다. ' }); } // 비밀번호 체크 const result = await bcrypt.compare(password, existUser.password); // 만약 패스워드가 일치 하지 않으면, false if (result) { return done(null, existUser); } else { return done(null, false, { reason: '비밀번호가 틀립니다.' }); } } catch (err) { console.log(err); return done(err); } } )); }
-
미해결스프링 핵심 원리 - 기본편
interface 파일들이 자동으로 .java 파일로 변환됩니다 ㅠㅠ
선생님 항상 감사한 마음으로 강의 잘 듣고 있습니다 : ) 다름이 아니라, 제가 어제 깃허브를 연동했는데, 그 이후로 interface 파일을 만들면 모두 자동으로 java파일로 변환되더라구요ㅠ 이전에 interface 파일로 만들어 놓은것들도 모두 .java 파일로 변환되어져 있습니다 ㅠㅠ 그래서 구현체에서 인터페이스파일을 impliment하여도 .java 파일로 변환되어져서 그런지 interface 파일에서의 메서드들도 받아오질 못합니다 ㅠㅠ 구글링해도 저같은 경우는 아직 못찾았습니다 ㅠㅠ 흑흑 선생님 시간되실 때 답변 부탁드립니당 ㅠㅠ
-
미해결자바 ORM 표준 JPA 프로그래밍 - 기본편
안녕하세요 강사님 JPA 관련해서 문의 드려요~
올려주신 강의 열심히 보고 있습니다 ^^ 실무에서 JPA를 적용하다보니 몇가지 벽을 만나서 문의드려요 1. JPA 에서 multisource 는 어떤식으로 구조를 잡아야 하나요? 예를 들어 read 는 slave, write는 master datasource 로 해야 하는데.. 이게 basepackage 로 같은 entity 들을 잡아도 될지 판단이 안서네요. 현재는 master, slave 로 나눈다음 같은 엔티티 클래스를 복제해서 각 datasource가 자신만의 엔티티를 가지고 있습니다. 2. 특정 datasource 를 생성자 주입으로 처리가 가능한지요? 예를 들어 아래 slaveDataSource 필드에 slave datasource 를 주입하려고 할때 @RequiredArgsConstructor 를 활용해서 하고 싶습니다. datasource 는 master용과 slave용 각각 별도의 Bean으로 등록해 두었습니다. @RequiredArgsConstructor public class SlaveDataSourceConfig { private final JpaProperties jpaProperties; private final HibernateProperties hibernateProperties; private final DataSource slaveDataSource; } 감사합니다.
-
미해결실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
정적 파일에 대한 질문입니다.
안녕하세요 팀장님! 자바의 걸음마를 떼고 방학되자마자 강의 보며 스프링을 익혀보고 있는 왕초보 대학생입니다!질문을 하고자 하는데 지난 무료강의를 마친 상태에서 제가 용어정리도 안되었고 대충 느낌상으로만 이해한 상태라 이해해주세요...ㅠㅠ 프론트쪽 개발자 분들이 html,css,js를 가지고 작업을 하면 그 파일들을 정적으로 가져와 스프링부트로 띄우고싶은데 상황에 따라 구조도 다르겠지만, 이 경우는 mapping 처리를 통해 받아 오는건가요?? 정확히 말하자면 스프링부트를 사용하는 백엔드 개발자가 프론트 개발자와 협업하는 방법이 궁금합니다!