Sequlize & Express. P1


Posted by Rich on 2021-08-11

這篇的目的是 express 配上 sequelize,把網站用 Node.js 跑起來~
Sequlize CLI 太好用了!所以也會用這個,開始吧!

npm init
先裝 sequelize
npm install sequelize
根據你的資料庫類型載對應的東西,詳情參考這裡
npm install --save mysql2
再裝 sequelize-cli
npm install --save sequelize
還有 express
npm install express --save
然後新增一個 index.js,內容如下:

const express = require('express')
const app = express()
const port = 5001

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

然後直接跑 node index.js 。上 localhost:5001 就可以看到 hello world 了。


Express 好了之後,要換 sequelize 了。
npx sequelize-cli init
然後會多很多檔案,config/config.json 裡面可以設定對應環境的資料庫資訊。
在本機上測試用,把 development 的帳號密碼改成 mysql 登入的帳號密碼,database 要是對應的名稱。
預設長這樣:

{
  "development": {
    "username": "root",
    "password": null,
    "database": "database_development",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}


根據官方文件,我們需要輸入指令讓它生成對應的資料庫。下面的 User 對應的是資料表名稱,--attributes,後面放欄位。
npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string

註:資料類型為數字的時候是 integer。

跑完後,migrations 裡面就會多一個檔案。詳細的設定都可再去裡面調,長這樣:

'use strict';
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      firstName: {
        type: Sequelize.STRING
      },
      lastName: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Users');
  }
};

記得還要 npx sequelize-cli db:migrate,資料才會真的進去資料庫。
之後去資料庫就可以看到建好的 User 囉。還會有 SequelizeMeta ,是用來記錄資料庫的改變。
下一篇講如何改變資料庫的內容。










Related Posts

猜數字

猜數字

學習 Git - 無法提交空資料夾?

學習 Git - 無法提交空資料夾?

Lidemy HTTP Challenge 破關紀錄

Lidemy HTTP Challenge 破關紀錄


Comments