好,會寫這一篇其實是因為我在 AWS 部署之前做過的 URL Shortener 專案時發生了問題,原因在於我原本是用 NoSQL 的 MongoDB 來管理資料,但既然要用 AWS 的 RDS 來託管資料勢必得更動原先專案裡的資料庫設定,所以咱就跑去學了 MySQL😐
前言 - MongoDB 版
Ok,要改動資料之前,要先來看看我之前是怎麼用 MongoDB 和它的 ODM Mongoose 來建立管理資料的資料庫的。首先,我們要管理的資料有:
- 使用者要轉換的網址。
- 轉換後的網址。
// 載入 mongoose
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const urlSchema = new Schema({
origin: {
type: String,
required: true
},
transfer: {
type: String
}
})
// 匯出資料型態
module.exports = mongoose.model('URL', urlSchema)
然後在 config/mongoose.js 中進行資料庫連線,像這樣:
// 載入 mongoose
const mongoose = require('mongoose')
// 僅在開發環境使用 dotenv
if(process.env.NODE_ENV !== 'production'){
require('dotenv').config()
}
// 連線到 mongoDB
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
// 取得資料庫連線狀態
const db = mongoose.connection
// 連線異常
db.on('error', ()=>{
console.log('mongoDB error!')
})
// 連線成功
db.once('open', ()=>{
console.log('mongoDB connected!')
})
// 匯出連線狀態
module.exports = db
然後這些東西呢,等等到 MySQL 版就通通不需要囉,呵呵!
MySQL 版 - 前置準備
接下來,要來把資料管理改成 MySQL,在那之前要先把需要的東西安裝好。
- MySQL 資料庫與 Workbench。在安裝時記得選擇 "Full",那就會連同 Workbench 一同安裝。
- 打開 Workbench,咱們來建立資料庫囉!
drop database if exists url_shortener;
create database url_shortener;
use url_shortener;

- 現在終端機 cd 到專案路徑,安裝 mySQL、Sequelize、和 Sequelize CLI。Sequelize 是 MySQL 的 ORM。Sequelize CLI 是 Sequelize 提供的一系列事先設定好的腳本,可以非常快速地幫我們進行資料庫設定。
npm install mysql2 sequelize sequelize-cli
MySQL 版 - 設定篇
該裝的都裝完了,來設定吧!
- 初始化設定,這裡執行完會發現 Sequelize 非常貼心地把需要的資料夾與設定檔都建完了,包括:config/config.json、models/index.js、migrations、seeders。
npx sequelize init

- 打開 config/config.json,可以看到 Sequelize 把資料庫連線的相關設定都寫好了,我們不用像寫 Mongoose 一樣自己從頭寫設定啦!進去後找到 development 環境,在 password 與 database 輸入自己的密碼以及要連線的資料庫名稱。如果有 operatorsAliases 設定記得刪掉。最後會看起來像這樣:

- 設定 model。這裡一樣會用 Sequelize CLI 來幫忙建立 model。建立完會發現多出 models/url.js 和 migrations/XXX-create-url.js 兩個檔案。
npx sequelize model:generate --name Url --attributes origin:string,transfer:string
- 打開那個 migrations/XXX-create-url.js,來把必填的項目加上 allowNull: false,在這裡我設定一定要存入一個原始未轉換的網址。

- 執行資料庫遷徙。現在就是把我們在專案中寫入的設定通知 MySQL 資料庫來幫忙建立資料囉 ~
npx sequelize db:migrate
- 現在回到 Workbench,執行
select * from urls;
,看到類似下面這張圖就是成功了:

- 改完資料庫設定,現在必須把原本引用 Mongoose 的 config 和 model 的地方給改掉,以首頁為例:
// 引入資料庫設定
const db = require('../../models')
const Url = db.Url
// 更改原本的操作
router.post('/shortener', async (req, res)=>{
try{
const originUrl = req.body.url
const data = await Url.findOne({where: {origin: originUrl}})
if(data){
res.render('shortener', {transfer: data.transfer})
}else{
const shorterUrl = urlShortener()
Url.create({origin: originUrl, transfer: shorterUrl})
.then(() => res.render('shortener', { transfer: shorterUrl }))
.catch(error => console.log(error))
}
}catch (error){
console.log(error)
}
})
- 現在咱們測試看看,實際測試一個網址,看到資料庫確實存入使用者輸入的網址以及轉換後的網址啦!嗯,大功告成啦!

下篇回到 AWS 部署...www