--- tags: Node.js 直播班 - 2023 春季班 --- # 🏅 Day 18 - 取得資料搭配 sort()、limit() Mongoose 的 `sort()` 可使用物件寫法 ``` sort({ field: 'asc', test: -1 }) // field 欄位以升序排列,test 欄位以降序排列 ``` ,也可只帶入欄位名稱(欄位名稱前加上 - 代表降序排列) ``` query.sort('field -test'); // field 欄位以升序排列,test 欄位以降序排列 ``` Mongoose 的 `limit()` 可直接帶入數字,如:`.limit(20)` 代表最多呈現 20 筆資料 ### 參考資源 - [Query.prototype.sort()](https://mongoosejs.com/docs/api/query.html#query_Query-sort) - [Query.prototype.limit()](https://mongoosejs.com/docs/api/query.html#query_Query-limit) - 課程影音「query - 取得網址參數」 ## 題目(將答案寫在 HackMD 並提交至回報區) 在 GET posts 網址列帶入排序及限制筆數的參數 並運用 Express 提供的 req.query 取得網址列的參數,將尋找到符合的資料設定排序及呈現指定資料數量 提交範例 ```javascript // routes/posts.js router.get('/', async function(req, res, next) { // 使用三元運算子判斷是否為 asc (由舊至新),若是則由舊至新排列,否則由新至舊排列 const timeSort = // 帶入網址列的參數 const limit = const post = await Post.find()/* 請填入答案 */ res.status(200).json({ status: 'success', data: { post } }); }) ``` 可自行建立專案或使用先前提供的[專案](https://github.com/dogwantfly/express-add-post)測試是否正確運作 ## 回報流程 將答案連結貼至底下回報就算完成了喔! 解答位置請參考下圖(需打開程式碼的部分觀看)  <!-- 解答: ```javascript router.get('/', async function(req, res, next) { const timeSort = req.query.timeSort === 'asc' ? 'createdAt' : '-createdAt'; const limit = req.query.limit; const post = await Post.find().sort(timeSort).limit(limit); res.status(200).json({ status: 'success', data: { post } }); }) ``` --> 回報區 --- | 報數 | 組別/Discord 名字 | Codepen/HackMD/其他回饋 | |:----:|:-----------------------:|:-------------------------------------------------------------------------:| | 1 | 北 10 組 / Benson | [Github - Day 18](https://github.com/ioveasdkre/HexschoolOperation/tree/main/NodejsEnterpriseClass/day40-tasks/day18/app.ts) | | 2 | 中 4 組 / jimkk159 | [HackMD - Day 18](https://hackmd.io/t5aBARcNQNC4umXSOs4a4Q) | | 3 | 北 12 組 / Sam Lin | [GitHub - Day 18](https://github.com/samlin1122/hex-school/blob/main/daily-challenges/day18.js) | 4 | 北 13 組 / Louisa | [GitHub - Day 18](https://github.com/louisa0416/NodejsEnterpriseClass/tree/master/daily-task/day18#readme) | | 5 | 南 1 組 / hiYifang | [HackMD - Day 18](https://hackmd.io/@gPeowpvtQX2Om6AmD-s3xw/ryrhdUASq) |
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up