-
개인과제 : 시퀄라이저 include이제 막 슬픔 없이 십오 초 정도가 지났다 2022. 10. 11. 16:06
include:[모델명]
associate 되어 있는 모델을 따라 모든 정보가 다 나온다.
const express = require("express"); const authMiddleware = require("../middlewares/auth-middleware"); const { Users } = require("../models"); const { Posts } = require("../models"); const router = express.Router(); //...생략 //게시글 상세 조회 : 토큰필요 없음. router.get("/:postId", async (req, res) => { try { const postNum = req.params.postId; if (!postNum) { // TODO: Joi를 사용하지 않음 res.status(400).json({ message: '데이터 형식이 올바르지 않습니다.' }); return; } const post = await Posts.findOne({ where: { postId:postNum }, include: [Users], }); res.status(200).json({ data: post }); } catch (error) { const message = `${req.method} ${req.originalUrl} : ${error.message}`; console.log(message); res.status(400).json({ message }); } });
//썬더 클라이언트에 찍힌 응답 { "data": { "postId": 1, "userId": 367, "nickname": "popopo1", "title": "수정을한다면", "content": "수정을테스트해봐요", "likes": 7, "createdAt": "2022-10-11T02:33:16.000Z", "updatedAt": "2022-10-11T05:49:52.000Z", "User": { "userId": 367, "nickname": "popopo1", "password": "1234", "createdAt": "2022-10-11T02:32:00.000Z", "updatedAt": "2022-10-11T02:32:00.000Z" } } }
문제는, 정말 다 나온다는 거다.
패스워드까지.
include:[ { model:모델명, key:"외래키이름", attributes:["너가 보여주고 싶은 프로퍼티들"] } ]
//게시글 상세 조회 : 토큰필요 없음. router.get("/:postId", async (req, res) => { try { const postNum = req.params.postId; if (!postNum) { // TODO: Joi를 사용하지 않음 res.status(400).json({ message: '데이터 형식이 올바르지 않습니다.' }); return; } const post = await Posts.findOne({ where: { postId:postNum }, include: [{ //associate 이후 include 실험 model : Users, key: 'userId', attributes:['userId', 'nickname', 'createdAt','updatedAt'] }], }); res.status(200).json({ data: post }); } catch (error) { const message = `${req.method} ${req.originalUrl} : ${error.message}`; console.log(message); res.status(400).json({ message }); } });
//썬더클라이언트에 찍힌 응답 { "data": { "postId": 1, "userId": 367, "nickname": "popopo1", "title": "수정을한다면", "content": "수정을테스트해봐요", "likes": 7, "createdAt": "2022-10-11T02:33:16.000Z", "updatedAt": "2022-10-11T05:49:52.000Z", "User": { "userId": 367, "nickname": "popopo1", "createdAt": "2022-10-11T02:32:00.000Z", "updatedAt": "2022-10-11T02:32:00.000Z" } } }
패스워드를 빼고 마음대로 지정해줄 수 있다.
'이제 막 슬픔 없이 십오 초 정도가 지났다' 카테고리의 다른 글
팀과제 : ORM과 MySQL (0) 2022.10.15 개인과제 : 시퀄라이저 exclude (0) 2022.10.11 개인과제 : sequelize 세팅 (0) 2022.10.11 개인과제 : ERD 작업 - 좋아요 테이블의 경우 (0) 2022.10.11 개인과제 : PATCH method를 처음 구현해본 기념 (0) 2022.10.07