---
tags: Node.js 直播班 - 2022 春季班
---
# 🏅 Day 40
## 新增貼文留言功能
**實作前準備**
由於無法預期單則貼文的留言數量,因此留言的部分會另外使用 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)
### 題目(將答案寫在 HackMD 並提交至回報區)
**實作新增貼文留言功能**
**設計 POST `/posts/:id/comment` 路由**
* 需登入通過 JWT 驗證才能請求
- 新增傳入的留言,以及留言者 user ID、貼文 ID 新增至 comments collection 中
- 需回傳使用者新增的留言
回報流程
---
請同學依照下圖教學觀看解答、回報答案:

回報格式:請在「回報區」貼上 CodePen 或 HackMD 連結回報答案 (為了統計人數,請同學依序加上「報數」)
<!-- 解答
範例參考
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
}
});
}))
```
-->
回報區
---
| 報數 | 組別 / 名字 | codepen / hackMD / 其他回饋 |
| ---- | ----------- | ------------------ |
|1| 第五組 @ Hazel | [HackMD@Hazel](https://hackmd.io/@hazelwu/day40)|
|2| 第3組 / Hobby | [HackMD](https://hackmd.io/@hobbyling/day40)|
|3| 第 14 組|East | [HackMD](https://hackmd.io/ElVQJjKFTnqStOgJfXQiBQ)|
|4| 第 4 組|苡安 | [HackMD](https://hackmd.io/WyibRAHjTqK5n3UxUOklgQ)|
|5| 第 11 組|Han Lai | [HackMD]([https://hackmd.io/WyibRAHjTqK5n3UxUOklgQ](https://hackmd.io/dIZzftFmQeyEB5cfCerikQ?view))|
|6| 第 16 組|皓皓 | [HackMD](https://hackmd.io/@cutecat8110/ryaJ_b4ic)|