總結
以下是本次作業處理到的主要問題:
- 透過一行腳本在多個資料庫個別產生種子資料
- 透過 mongoose 在 mongoDB 中 join 兩組 collections 之間的資料
- 使用 axios 進行 ajax 請求,根據使用者選擇的組別顯示相對應的帳目資料(例:選擇「休閒娛樂」的帳目資料,則畫面僅會顯示該類別的帳目,並消費總金額會同步更新)
環境
node: 12.20.2express: 4.17.1express-handlebars: 5.3.2mongoose: 5.12.9os: Windows_NT 10.0.18363 win32 x64筆記
專案結構

透過一行腳本在多個資料庫個別產生種子資料
npm run腳本如右:"seed": "node models/seeds/categorySeeder.js && node models/seeds/recordSeeder.js"
兩份種子腳本的原始碼如下:
node models/seeds/categorySeeder.js執行完畢後,需確保腳本停止,方可開始執行node models/seeds/recordSeeder.js- 在
categorySeeder.js中,待Categories.create()完成後,串接.then()來停止 db 連線 categorySeeder.js結束後,開始執行recordSeeder.js- 根據 MDN 的
forEach()polyfill,forEach()並沒有 await callback function 的機制,故改使用for...of來進行迴圈;相關參考文件如下: - 待
for...of執行完畢後,再關閉 db 連線,結束recordSeeder.js
對 mongoDB 進行類似 SQL 資料庫的 join 指令
- 第 49 行的
results,在前端透過 axios 接收後進行console.log(response.data)的內容如下:使用{"_id": "60a3a3f66d1cf025c09c5714","name": "早餐","category": "餐飲食品","date": "2021-05-18","amount": 80,"__v": 0,"iconPair": [{"_id": "60a3a865b6ccf51988c7cf9b","name": "餐飲食品","icon": "<i class=\"bi bi-cup-straw\"></i>","__v": 0}]}{"_id": "60a3a3f66d1cf025c09c5715","name": "午餐","category": "餐飲食品","date": "2021-05-18","amount": 120,"__v": 0,"iconPair": [{"_id": "60a3a865b6ccf51988c7cf9b","name": "餐飲食品","icon": "<i class=\"bi bi-cup-straw\"></i>","__v": 0}]}{"_id": "60a3a3f66d1cf025c09c5716","name": "晚餐","category": "餐飲食品","date": "2021-05-18","amount": 100,"__v": 0,"iconPair": [{"_id": "60a3a865b6ccf51988c7cf9b","name": "餐飲食品","icon": "<i class=\"bi bi-cup-straw\"></i>","__v": 0}]}$lookup關聯出的結果可透過鍵值iconPair取得 - 相關參考文件:
- How to join two collections in mongoose
- $lookup (aggregation)
- $sum (aggregation):
$sum可搭配aggregation來直接回傳某欄位的總計值,本次未使用
使用 axios 進行 ajax 請求

- 若使用 axios 進行 POST request 的話,需搭配
body-parser,並加上app.use(bodyParser.json()),否則無法取得 POST request 送出的資料// app.js中需加入以下兩組middlewareapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true })); - 參考文件如下: