[항해99] 44일차 몽구스 populate
항해 99
44일 차:
API마무리하는데 너무 오래 걸렸다.
일단 mongoose로 관계 설정 을해 주는 부분이 어제 배워놓고 실전에서 써보려고 하니깐 복잡한 게 많았다. 아니 복잡한 게 아니라 내가 멍청해서 쉬운 solution을 나 두고 인터넷 검색만 하루 종일 했다.
기본적인 object , array개념도 모르는 것 같아서 슬픈 하루였다.
object는 객체 , key :value..
array가 배열. [apple, banana]..
이번에 클론 코딩에서는 내가 백앤드 배포를 했는데, 생각보다 재밌었다. 이게 한 명이 aws배포를 하면 에러 메시지를 처리하고 파일 질라로 다시 업데이트를 하느라 배포한 사람이 주가 돼서 디버깅을 하는데, 저번 주에 하는 걸 보고 이걸 내가 할 수 있을지 걱정이었지만 생각보다 재밌었다.
post의 연결되는 코멘트 부분이 comments 하고 array로 감싸줬다.
그래야 포스트에 해당하는 코멘트들이 array형태로 추가가 된다.
const mongoose = require("mongoose");
const { Schema } = mongoose
const getCurrentDate = require("../utils/moment")
const PostSchema = new Schema({
_id: Schema.Types.ObjectId,
postId: Number,
userInfo: {
firstName: String,
lastName: String,
profilePic: String,
},
content: {
text: String,
picture: String,
createdAt: { type: Date, default: Date.now }
},
comments: [{
type: Schema.Types.ObjectId,
ref: 'Comment'
}],
like: {
likeCnt: Number,
userList: [{ firstName: String, lastName: String }]
},
})
module.exports = mongoose.model('Post', PostSchema);
코멘트 작성 api
router.post('/', async (req, res) => {
// comments writer info get from token
const { commentText, postId } = req.body
const _id = new mongoose.Types.ObjectId()
const firstName = "skyler"
const lastName = "Bang"
try {
const allComments = await Comment.find({})
const commentId = allComments.length + 1
const newComment = await Comment.create({ _id, postId, commentId, commentText, firstName, lastName });
const post = await Post.findOne({ postId })
if (post) {
post.comments.push(newComment._id)
post.save()
//await Post.findOneAndUpdate(postId, { comments })
}
res.status(201).send({ commentId });
} catch (err) {
res.status(400).send(err);
}
});
포스트와 해당 포스트의 코멘트를 불러오는 api
populate안에 argument는 해당하는 스케마의 연결되는 부분.
위에서 post에서 연결되는 부분이 comments이니깐 comments로 써줘 야한다!!!
router.get("/", async (req, res) => {
console.log(" Getting all the post API")
const list = await Post.find({}).sort({ postId: -1 }).populate('comments')
res.status(200).json(list)
})
- mongoose로 기능 구현을 하는 것까지 official document와 블로그 글들을 통해 잘 배워놓고
응용하는 부분에서 시간이 너무 많이 걸렸다. 아직까지도 기초가 모자라서 헤매는 것 같다.
argument vs parameter?
'IT > Bootcamp 항해99' 카테고리의 다른 글
[항해99] 46일차 살려주세요. (5) | 2021.07.23 |
---|---|
[항해99] 45일차 클론코딩 (6) | 2021.07.21 |
[항해99] 43일차 API완성 JWT토큰 , populate, ref mongoose (0) | 2021.07.20 |
[항해99] 42일차 API설계와 포스트맨 사용법 (0) | 2021.07.18 |
[항해99] 40일 & 41일차 클론코딩 (3) | 2021.07.18 |