Node.js 1주차 과제 트러블 슈팅
- 1주차 과제 첫번째 항목인 게시글 작성 API를 작성하려고 했다. 어디서 get과 post 요청을 작성할때는 post요청을 데이터를 db에 먼저 저장하고 데이터를 불러오는 get요청을 나중에 작성하라는 내용이 기억나서 데이터를 db에 넣어보기로 했다
app.js
const express = require('express');
const app = express();
const port = 3000;
const postsRouter = require('./routes/posts')
const commentsRouter = require("./routes/comments")
const connect = require("./schemas")
connect()
//데이터 파싱 미들웨어
app.use(express.json())
//추가경로 미들웨어 공통경로 /work 추가
app.use("/work", [postsRouter, commentsRouter]);
app.listen(port, () => {
console.log(port, '포트로 서버가 열렸어요!');
});
posts.js
const express = require("express")
const router = express.Router()
const Posts = require("../schemas/posts.js")
//1. 게시글 조회 api
router.get('/posts/', (req, res) => {
res.json({})
})
//2. 게시글 작성 api
router.post("/posts/", async (req, res) => {
//에러 처리어떻게??
const { postId, user, password, title, createdAt, content } = req.body
const posts = await Posts.find({ postId })
if (posts.length) {
return res.status(400).json({ message: '데이터 형식이 올바르지 않습니다.' })
} else {
const createdPosts = await Posts.create({ _postId: postId, user, password, title, createdAt, content })
res.status(200).json({ "message": "게시글을 생성하였습니다.", data: createdPosts })
}
})
module.exports = router;
../schemas/posts.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema; // 추가
//스키마 내용 정의
const postsSchema = new Schema({ // 수정
_postId: {
type: String,
// unique: true,
},
user: {
type: String,
// required: true,
},
password: {
type: Number,
// required: true,
},
title: {
type: String,
},
content: {
type: String,
},
createdAt: {
type: Date,
},
});
module.exports = mongoose.model("Posts", postsSchema);
입력 받을 데이터
{
"user": "Developer",
"password": "1234",
"title": "안녕하세요",
"content": "안녕하세요 content 입니다."
}
입력후 실행하고싶은 동작
- 아래 메시지 출력
{"message": "게시글을 생성하였습니다."}
- db에 지정한 스키마 형식대로 데이터 저장
에러
- localhost:3000/work/posts/ 경로로 데이터 입력후 post요청시 400에러 발생,
시도
- schemas/posts.js 파일에서 변수 postsSchema에 들어있는 _postId의 속성중 required:를 true나 false로 조정해봄 => _postId 스키마의 속성이 잘못된것 같다는 생각
- _postId 스키마의 속성중 unique의 값을 true, false로 조정해봄.
오류로 의심가는부분
- 아래 코드에서 에러를 처리하는 조건문이 잘못 됐 을 수도 있을것 같다는 의심이든다. 근데 어떻게 해결해야 할지는 모름
router.post("/posts/", async (req, res) => {
//에러 처리어떻게??
const { postId, user, password, title, createdAt, content } = req.body
const posts = await Posts.find({ postId })
if (posts.length) {
return res.status(400).json({ message: '데이터 형식이 올바르지 않습니다.' })
} else {
const createdPosts = await Posts.create({ _postId: postId, user, password, title, createdAt, content })
res.status(200).json({ "message": "게시글을 생성하였습니다.", data: createdPosts })
}
})
const postsSchema = new Schema({ // 수정
_postId: {
type: String,
// unique: true,
},
user: {
type: String,
// required: true,
},
password: {
type: Number,
// required: true,
},
title: {
type: String,
},
content: {
type: String,
},
createdAt: {
type: Date,
},
});
- Shchema 설정에서 _postId 스키마의 설정이 잘못된거 같다는 의심이 계속 든다.
이해가 안가는 부분
- 데이터를 입력할때 오류가 났는데 studio 3T에는 데이터가 입력된 값이 있었다. 아마 내 예상에는 내가 방금 넣은 값이 아니라 작업하면서 이것저것 만져보다 우연히 db에 들어가게 된 것 같다. 그 이후로 데이터가 다시 db에 들어가지 않았다. 데이터가 왜 들어간건지??
- postsShema에서 정의한 스키마값들과 입력받은 데이터값이 key value가 다를때 어떻게 처리해야 하는지 잘 이해가 가지않는다
- 아래 이미지에서 스키마.js에서는 _postId값을 정의 했는데 db에 입력된 스키마에는 _id로만 입력되어있다 왜 그런지 모르겠다.
수정전 posts.js
- req.body에 입력된 데이터
{
"user": "Developer",
"password": "1233",
"title": "안녕하세요" ,
"content": "안녕하세요 content 입니다."
}
- body에 입력된 데이터에는 postId라는 key값이 없었는데 내가 postId라는 데이터를 받아온다고 선언해서 없는 데이터를 로 db에서 가져오려는 코드를 짰다. 그래서 첫번째로 posts라는 변수를 삭제 해줬다. 그 아래 할당된 _postId도 모두 삭제했다.
- 여기서 ({ postId }) 의 의미는 db에서 key와 value가 같은 값을 가져온다는 의미였다. db에는 postId라는 key값이 아예 존재 하지 않았기 때문에 여기서 변수 posts에는 undefined가 할당된 상태였다.
const posts = await Posts.find({ postId}) //undefined
- 조건문에서는 변수 posts의 값이 undefined로 할당된 상태였기 때문에 undefined.length === truthy 이기때문에 첫번쨰 조건에서 400에러 메세지를 반환하고 조건문이 끝나는 코드가 됐었다
//2. 게시글 작성 api
router.post("/posts/", async (req, res) => {
//에러 처리어떻게??
const { postId, user, password, title, createdAt, content } = req.body
const posts = await Posts.find({ postId })
if (posts.length) {
return res.status(400).json({ message: '데이터 형식이 올바르지 않습니다.' })
} else {
const createdPosts = await Posts.create({ _postId: postId, user, password, title, createdAt, content })
res.status(200).json({ "message": "게시글을 생성하였습니다.", data: createdPosts })
}
})
수정후 posts.js
- 데이터로 받아올 값중에 _postId 값은 없기때문에 구조분해로 할당한 _postId 전부 삭제
- db에서 찾으려고 하는 값이 있는게 아니기 때문에 posts변수 삭제
- 데이터가 이상한 경우 에러를 분기 처리 하기 위해 try..catch 문이나 조건문으로 데이터입력을 성공했을때와 실패했을때를 나눠서 처리해주기.(데이터 입력을 성공했을때 얼리리턴)
//2. 게시글 작성 api
router.post("/posts/", async (req, res) => {
//에러 처리어떻게??
const { user, password, title, content, createdAt } = req.body
// console.log(req.body)
const createdPosts = await Posts.create({ user, password, title, createdAt, content })
res.status(200).json({ "message": "게시글을 생성하였습니다.", data: createdPosts })
// if(){
// }
// return res.status(400).json({ message: '데이터 형식이 올바르지 않습니다.' })
})
수정전 Schema/posts.js
- Schema/posts.js 에서는 _postId라는 컬럼을 생성한다고 설정해주었지만 입력받은 데이터에는 _postId를 입력받지 않았기 때문에 _postId컬럼 삭제.
- 필수로 입력받아야하는 데이터인 user, title, password, content 컬럼에 required: true 속성을 줘서 데이터가 입력되지 않았을때 에러처리를 하도록 설정
- 스키마의 설정을 바꿨을때는 studio 3T에서 db를 drop하고 다시 db를 생성해야함 왜냐하면 Schema/posts.js 에서는 생성된 스키마의 속성만 설정해주는 것이기 때문에 studio 3T에서 컬럼의 값을 바꾸거나 속성을 변경하려면 db를 drop하고 db를 재생성해줘야 속성이 적용된다.
- studio 3T에 생성된 _id의 값은 고유한 값은 primary key 값이므로 몽고db에서 자체적으로 생기는 고유한 값이다 그래서 이 컬럼 값을 변경하거나 임의로 조정 할 수 없다.
- 1부터 차례대로 들어가는 값을 생성하려면 autoincreament라는 npm 라이브러리를 사용하여 입력된 데이터 순서대로 값을 1씩 증가 시키는 npm라이브러리가 있다.
- 게시판에서 게시판글을 상세조회하고 오름차순, 내림차순으로 정렬하려면 cretedAt 값을 활용하여 입력된 데이터의 날짜,시간별로 정렬해 줄 수 있다.
const postsSchema = new Schema({ // 수정
_postId: {
type: String,
// unique: true,
},
user: {
type: String,
// required: true,
},
password: {
type: Number,
// required: true,
},
title: {
type: String,
},
content: {
type: String,
},
createdAt: {
type: Date,
},
});
수정후 Schema/posts.js
const postsSchema = new Schema({ // 수정
user: {
type: String,
// required: true, // null 여부
},
password: {
type: Number,
// required: true,
},
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
createdAt: {
type: Date,
default: Date.now, // 기본값
//autoincreament
},
});
소스코드주소
https://github.com/ystar5008/node-personal-work-prac
GitHub - ystar5008/node-personal-work-prac: 항해99 Node.js 주특기 개인과제 레포
항해99 Node.js 주특기 개인과제 레포. Contribute to ystar5008/node-personal-work-prac development by creating an account on GitHub.
github.com
'개발일지' 카테고리의 다른 글
개발일지 33일차 (2) | 2023.04.18 |
---|---|
개발일지 32일차 (0) | 2023.04.18 |
개발일지 2주차 WIL (0) | 2023.04.16 |
개발일지 30일차 (3) | 2023.04.16 |
내가보려고 만든 git명령어 (0) | 2023.04.15 |