ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 개인과제 : 시퀄라이저 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"
        }
      }
    }

    패스워드를 빼고 마음대로 지정해줄 수 있다.

     

     

Designed by Tistory.