- ์ด๋ฒ ํฌ์คํธ์์๋ MongoDB์ populate ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ๊ฒ์๋ฌผ ์กฐํ ์ ๋๊ธ๋ ํจ๊ป ๋ถ๋ฌ์ค๋ ๋ฐฉ๋ฒ์ ๋ํด ์์๋ณด๊ฒ ์!
1. ์คํค๋ง ์ค๊ณ
- ์ฐ์ , ๊ฒ์๋ฌผ(Post)๊ณผ ๋๊ธ(Comment)์ ์คํค๋ง๋ฅผ ์ ์ํด์ผ ํจ.
1) ๊ฒ์๋ฌผ ์คํค๋ง
// post.js
const mongoose = require("mongoose");
const postSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
text: {
type: String,
required: false,
trim: true,
},
images: [
{
type: String,
required: true,
},
],
createdAt: {
type: Date,
default: Date.now,
},
comments: [{ // ๋๊ธ์ ์ํ ํ๋ ์ถ๊ฐ
type: mongoose.Schema.Types.ObjectId,
ref: "Comment",
}],
});
const Post = mongoose.model("Post", postSchema);
module.exports = { Post };
2) ๋๊ธ ์คํค๋ง
// comment.js
const mongoose = require("mongoose");
const commentSchema = new mongoose.Schema({
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
required: true,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
text: {
type: String,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
const Comment = mongoose.model("Comment", commentSchema);
module.exports = { Comment };
2. ๊ฒ์๋ฌผ ์กฐํ ๊ธฐ๋ฅ ๊ตฌํ
- ๊ฒ์๋ฌผ ์กฐํ API๋ฅผ ๊ตฌํํ์ฌ, ํน์ ๊ฒ์๋ฌผ๊ณผ ๊ทธ ๊ฒ์๋ฌผ์ ๋ฌ๋ฆฐ ๋๊ธ์ ํจ๊ป ๋ถ๋ฌ์ค๋ ๊ธฐ๋ฅ์ ์ถ๊ฐ.
- ์ด๋ฅผ ์ํด populate ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ๊ฑฐ์.
- populate ๋ฉ์๋๋ ์ด๋ค ์ปฌ๋ ์ ์์ ObjectId๋ฅผ ์ด์ฉํด์ ๋ค๋ฅธ ์ปฌ๋ ์ ์ ์ ๋ณด๋ฅผ ๋ด์ ์ถ๋ ฅํ ์ ์์
- ์์ธํ ์ค๋ช
1) ๊ฒ์๋ฌผ ์กฐํ ๋ผ์ฐํฐ
// getPost.js
const express = require("express");
const router = express.Router();
const { Post } = require("../../models/Post");
// ๊ฒ์๋ฌผ ์กฐํ
router.get("/:id", async (req, res) => {
const { id } = req.params;
try {
// ๊ฒ์๋ฌผ๊ณผ ๋๊ธ์ ํจ๊ป ๋ถ๋ฌ์ค๊ธฐ ์ํด populate ์ฌ์ฉ
const post = await Post.findById(id).populate("comments");
if (!post) {
return res.status(404).json({ message: "๊ฒ์๋ฌผ์ ์ฐพ์ ์ ์์ต๋๋ค." });
}
return res.status(200).json({ post });
} catch (error) {
return res.status(500).json({
message: "๊ฒ์๋ฌผ ์กฐํ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.",
error: error.message,
});
}
});
module.exports = router;
3. ๊ฒ์๋ฌผ ์กฐํ ์์
- ์์ API๋ฅผ ํธ์ถํ๋ฉด, ๊ฒ์๋ฌผ์ ๋ด์ฉ๊ณผ ํจ๊ป ๋๊ธ๋ค์ด ํฌํจ๋ ๊ฒฐ๊ณผ๋ฅผ ์ป์ ์ ์์.
# ์ถ๋ ฅ ์์
{
"post": {
"_id": "๊ฒ์๋ฌผ ์์ด๋",
"user": "์ฌ์ฉ์ ์์ด๋",
"text": "๊ฒ์๋ฌผ ํ
์คํธ",
"images": ["<https://example.com/image1.jpg>"],
"createdAt": "2024-11-02T06:59:29.107Z", # ๊ฒ์๋ฌผ ์์ฑ์ผ
"comments": [
{
"_id": "๋๊ธ ์์ด๋",
"user": "์ฌ์ฉ์ ์์ด๋",
"text": "์ฒซ ๋๊ธ์
๋๋ค!",
"createdAt": "2024-11-02T07:00:00.000Z" # ๋๊ธ ์์ฑ์ผ
},
{
"_id": "๋๊ธ ์์ด๋",
"user": "์ฌ์ฉ์ ์์ด๋",
"text": "๋ ๋ฒ์งธ ๋๊ธ์
๋๋ค!",
"createdAt": "2024-11-02T07:05:00.000Z" # ๋๊ธ ์์ฑ์ผ
}
]
}
}
4. ๊ฒฐ๊ณผ ๐
- ๋ค์ ํฌ์คํธ์์๋ ๋๊ธ ์์ฑ ๊ธฐ๋ฅ์ ๋ํด ๋ค๋ค๋ณผ๊ฑฐ์!!