---
tags: Node.js 直播班 - 2023 春季班
---
# 🏅 Day 39 - 新增貼文留言功能
**實作前準備**
由於無法預期單則貼文的留言數量,因此留言的部分會另外使用 collection 存放
Schema 設定可參考[範例程式碼](https://github.com/gonsakon/express-week4-sample/blob/week8/models/commentsModel.js)
```javascript
const commentSchema = new mongoose.Schema(
{
comment: {
type: String,
required: [true, 'comment can not be empty!']
},
createdAt: {
type: Date,
default: Date.now
},
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
require: ['true', 'user must belong to a post.']
},
post: {
type: mongoose.Schema.ObjectId,
ref: 'Post',
require: ['true', 'comment must belong to a post.'],
}
}, { versionKey: false }
);
```
由於 Comments 存放在另一個 collection,因此若取得貼文時需要顯示出相關留言串,需另外在 Post Schema 中加入**虛擬欄位**
而此虛擬欄位 comments 會關聯 Comment Model 的 post 欄位及 Post Model 的 _id 欄位,找出所有該貼文 ID 的留言
```javascript
postSchema.virtual('comments', {
ref: 'Comment',
foreignField: 'post',
localField: '_id'
});
```
需注意當 document 被轉為 JSON 或 Object 資料時,是不包含虛擬欄位的,因此需記得在貼文 Schema 加入
```javascript
toJSON: { virtuals: true },
toObject: { virtuals: true },
```
### 參考資源
- [Mongoose v6.3.4: Mongoose Tutorials: Mongoose Virtuals](https://mongoosejs.com/docs/tutorials/virtuals.html)
- [Mongoose Middleware - Pre](https://mongoosejs.com/docs/middleware.html#pre)
## 題目
**實作新增貼文留言功能**
**設計 POST `/posts/:id/comment` 路由**
* 需登入通過 JWT 驗證才能請求
- 新增傳入的留言,以及留言者 user ID、貼文 ID 新增至 comments collection 中
- 需回傳使用者新增的留言
## 回報流程
將答案連結貼至底下回報就算完成了喔!
解答位置請參考下圖(需打開程式碼的部分觀看)

<!-- 解答:
範例參考
models/commentsModel.js
https://github.com/gonsakon/express-week4-sample/blob/week8/models/commentsModel.js
/routes/posts.js
https://github.com/gonsakon/express-week4-sample/blob/week8/routes/posts.js#L67-L83
```javascript=
// routes/posts.js
router.post('/:id/comment',isAuth, handleErrorAsync(async(req, res, next) => {
const user = req.user.id;
const post = req.params.id;
const {comment} = req.body;
const newComment = await Comment.create({
post,
user,
comment
});
res.status(201).json({
status: 'success',
data: {
comments: newComment
}
});
}))
```
-->
回報區
---
| 報數 | 組別/Discord 名字 | Codepen/HackMD/其他回饋 |
|:----:|:-----------------------:|:-------------------------------------------------------------------------:|
| 1 | 中 4 組 / jimkk159 | [HackMD - Day 39](https://hackmd.io/J-YQ3a3WTnWAEKBd0bvXtw) |