普通文組 2.5

Alpha Camp「2-3 老爸的私房錢(簡易記帳APP)」技術記錄

總結

以下是本次作業處理到的主要問題:

  • 透過一行腳本在多個資料庫個別產生種子資料
  • 透過 mongoose 在 mongoDB 中 join 兩組 collections 之間的資料
  • 使用 axios 進行 ajax 請求,根據使用者選擇的組別顯示相對應的帳目資料(例:選擇「休閒娛樂」的帳目資料,則畫面僅會顯示該類別的帳目,並消費總金額會同步更新)

環境

node: 12.20.2
express: 4.17.1
express-handlebars: 5.3.2
mongoose: 5.12.9
os: Windows_NT 10.0.18363 win32 x64

筆記

專案結構

本次專案的完整結構圖

透過一行腳本在多個資料庫個別產生種子資料

npm run腳本如右:"seed": "node models/seeds/categorySeeder.js && node models/seeds/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取得
  • 相關參考文件:

使用 axios 進行 ajax 請求

使用 ajax 來請求特定帳目群組的資料