---
tags: Node.js 直播班 - 2022 春季班
---
# 🏅 Day 36
## 新增、取消特定貼文讚
### 題目
實作[動態牆頁面](https://xd.adobe.com/view/c0763dbe-fc15-42e8-be0b-8956ed03e675-9525/screen/ace2ccc4-7e50-401b-998a-a14f49e87918/)**新增及取消貼文讚的功能**
**新增按讚**
設計 POST `/posts/:id/likes` 路由,需登入才能請求(id 為貼文 ID)
* 當使用者登入並驗證 JWT 正確,修改資料庫中該貼文的 likes 欄位,將使用者 ID 加入 likes 陣列中(使用 `$addToSet`,避免加入重複的使用者 ID)
* 若新增成功,回傳成功訊息及修改的貼文 ID、新增的使用者 ID
**移除按讚**
設計 DELETE `/posts/:id/likes` 路由,需登入才能請求(id 為貼文 ID)
* 當使用者登入並驗證 JWT 正確,修改資料庫中該貼文的 likes 欄位,將使用者 ID 由 likes 陣列中移除(使用 `$pull`)
* 若移除成功,回傳成功訊息及修改的貼文 ID、已移除的使用者 ID
**使用 Postman 測試是否正確運作**
**將程式碼片段貼至 HackMD 並回報**
回報流程
---
請同學依照下圖教學觀看解答、回報答案:

回報格式:請在「回報區」貼上 CodePen 或 HackMD 連結回報答案 (為了統計人數,請同學依序加上「報數」)
<!-- 解答
範例參考 https://github.com/gonsakon/express-week4-sample/blob/week8/routes/posts.js#L40-L65
```javascript=
// routes/posts.js
const router = express.Router();
const Post = require('../models/postsModel');
const { isAuth } = require('../service/auth');
// 新增按讚
router.post('/:id/likes',isAuth, handleErrorAsync(async function(req, res, next) {
const _id = req.params.id;
await Post.findOneAndUpdate(
{ _id},
{ $addToSet: { likes: req.user.id } }
);
res.status(201).json({
status: 'success',
postId: _id,
userId: req.user.id
});
}));
// 移除按讚
router.delete('/:id/likes',isAuth, handleErrorAsync(async(req, res, next) => {
const _id = req.params.id;
await Post.findOneAndUpdate(
{ _id},
{ $pull: { likes: req.user.id } }
);
res.status(201).json({
status: 'success',
postId: _id,
userId: req.user.id
});
}))
```
-->
回報區
---
| 報數 | 組別 / 名字 | codepen / hackMD / 其他回饋 |
| ---- | -------------- | -------------------------------------------------- |
| 1 | 第 14 組|East | [HackMD](https://hackmd.io/XH_66fCNTGmVc2nW2GXxhA) |
| 2 | 第 4 組|苡安 | [HackMD](https://hackmd.io/ULYEyOJZSeOb9Mh946gAHw) |
| 3 | 第 9 組 / konstante |[HackMD](https://hackmd.io/SaJDvR0cQA6pEgADsWxh3g?edit) |
| 4 | 第 5 組@Hazel|[HackMD@Hazel](https://hackmd.io/@hazelwu/day36) |
| 5 | 第 2 組 wendy | [HackMD](https://hackmd.io/80FIwll1QUa4u0-WoBv-hQ#20220526)|
| 6 | 第 3 組|Hobby | [HackMD](https://hackmd.io/@hobbyling/day36) |
| 7 | 第 12 組|Jimmy | [HackMD](https://hackmd.io/MifvTVXRTEiosQ18JDK0KQ) |
| 8 | 第 11 組|Han Lai | [HackMD](https://hackmd.io/0McS8NS0T8uW5s9FwAZ3Cg?view) |
| 9 | 第 16 組|皓皓 | [HackMD](https://hackmd.io/@cutecat8110/Sk4u28boc) |