koa --- 使用Sequelize連接mysql

Sequelize介紹

  • 為了快捷開發,社區出現了一系列的ORM(Object Relational Mapping)類庫
  • ORM的字面意思為對象關系映射,它提供了概念性的、易于理解的模型化數據的方法。通過ORM,可以降低操作數據庫的成本。開發者不需要通過編寫SQL腳本來操作數據庫,直接通過訪問對象的方式來查詢、更新數據。這樣做極大地提升了開發效率,降低了開發門檻。缺點也很明顯,不夠高效
  • 在Node.js中,一般采用Sequelize這個ORM類庫來操作數據庫.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('databaseName', 'userName', 'password', {host:'localhost',  // 數據庫服務地址dialect: 'mysql'   // SQL語言類型
});
sequelize.authenticate().then(()=>{console.log('Connected');
}).catch(err=>{console.error('Connect failed');
})
  • 使用docker創建一個數據庫.
    使用docker-compose.yml寫配置文件如下:
version: '3.1'
services:mysql:image: mysqlcommand: --default-authentication-plugin=mysql_native_passwordrestart: alwaysenvironment:MTSQL_ROOT_PASSWORD: exampleports:- 3306:3306adminer:image: adminerrestart: alwaysports:- 8080:8080

使用如下命令生成docker

docker-compose up

連接數據庫

const Sequelize = require('sequelize');
const sequelize = new Sequelize('數據庫名稱','用戶名(默認:root)','密碼(docker-compose.yml中設置的)', {host:'localhost',dialect: 'mysql'
});
sequelize.authenticate().then(()=>{console.log('Connected');
})
.catch(err=>{console.error('Connect failed', err);
})

定義模型

  • 常用
const Category = sequelize.define('category', {id: Sequelize.UUID,   // 定義id字段,類型為UUIDname: Sequelize.STRING    // 定義name字段,類型為String
})
  • 給模型加約束條件
const Project = sequelize.define('project', {name: {type: Sequelize.STRING,   // 定位類型為StringallowNull: false,   //不能為空unique: true   // 必須唯一,不允許重復},date: {type: Sequelize.DATE,defaultValue: Sequelize.NOW     // 設置為當前時間}
})
  • 給字段定義Getter和Setter方法:
const Custom = sequelize.define('custom', {name: {type: Sequelize.STRING,get(){const title = this.getDataValue('title');return `${this.getDataValue('name')} (${titile}) `}},title: {title: Sequelize.STRING,set (val) {this.setDataValue('title', val.toUpperCase())}}
})

查詢數據

  • 查詢所有
    await Product.findAll()

  • 查詢name和data字段
    await Project.findAll({ attributes: ['name', 'date'] })

在使用一個庫的時候,可以先把庫的方法包裝以下,變成自己的庫

  • 在下面的栗子中,首先把Sequelize庫中的API抽離出來,根據實際的業務變成自己項目的函數.通過按需的方式引入到業務中.
  • 這樣做利于維護,(例如,Sequelize庫變化了,不需要整個項目尋找使用到該接口的函數,或者具體改變了,重新改變接口)

栗子

  • 項目結構如下:
    在這里插入圖片描述
  • 設計Customer表的類型,如下:
  • /mysql/model/custom.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('custom', 'root', 'example', {dialect:'mysql'
});
// 定義Customer模型
const Customer = sequelize.define('customer',{id:{type: Sequelize.UUID,unique: true,primaryKey: true,allowNull: false},name: {type: Sequelize.STRING,allowNull: false},sex: {type: Sequelize.ENUM(['男','女']),allowNull: false},address:{type: Sequelize.STRING},email: {type: Sequelize.STRING,allowNull: false},phone: {type: Sequelize.STRING},country:{type: Sequelize.STRING},city: {type:Sequelize.STRING}
});
  • /mysql/db.js中,對表的功能進行加工
const { Customer } = require('./model/custom');const { Op } = require('sequelize');
async function getAllCustomers() {return Customer.findAndCountAll({attributes: ['id', 'name', 'sex', 'fulladdress'],order: [['updatedAt', 'DESC']]})
}
async function getCustomerById(id) {return Customer.findById(id);
}async function getCustomerByName(name) {return Customer.findAll({where: {name: {[Op.like]: `${name}`}}})
}async function updateCustomer(id, customer) {const item = await getCustomerById(id)if (item) {return item.update(customer);} else {throw new Error('the customer with id ${id} is not exist');}
}async function createCustomer(customer) {return Customer.create(customer);
}async function deleteCustomer(id) {const customer = await getCustomerById(id);if (customer) {return customer.destroy();}
}
  • /mysql/app.js中對對應的路由設置數據庫的操作方法(路由層還未抽離出來)
const {getAllCustomers,getCustomerById,getCustomerByName,createCustomer,updateCustomer,deleteCustomer
} = require('./db');
const koa = require('koa');
const app = new koa();
const router = new require('koa-router')();
const bodyParser = require('koa-bodyparser');app.use(async (ctx, next) => {try {await next();} catch (ex) {// ctx.type = jsonMIME;ctx.body = {status: -1,message: ex.message}}
})router.get('/customer', async ctx => {const customers = await getAllCustomers();// ctx.type = jsonMIME;ctx.body = {status: 0,data: customers};
});router.get('/customer/:id', async ctx => {const customer = await getCUstomerById(ctx.params.id);// ctx.type = jsonMIME;ctx.body = {status: 0,data: customer};
});router.get('/customer/name/:name', async ctx => {const customer = await getCUstomerByName(ctx.params.name);// ctx.type = jsonMIME;ctx.body = {status: 0,data: customer};
});router.post('/customer', async ctx => {const customer = ctx.body;await createCustomer(customer);// ctx.type = jsonMIME;ctx.body = {status: 0};
});router.put('/customer/:id', async ctx => {const id = ctx.params.id;const customer = ctx.body;await updateCustomer(id, customer);// ctx.type = jsonMIME;ctx.body = {status: 0};
});router.delete('/customer/:id', async ctx => {await deleteCustomer(ctx.params.id);// ctx.type = jsonMIME;ctx.body = {stauts: 0};
});app.use(bodyParser());
app.use(router.routes());app.listen(3000, async () => {console.log('Server is running at http://localhost:3000');
})

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/250483.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/250483.shtml
英文地址,請注明出處:http://en.pswp.cn/news/250483.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java Web Jsp

Java Web Jsp JSP全稱Java Server Pages&#xff0c;是一種動態網頁開發技術。它使用JSP標簽在HTML網頁中插入Java代碼。標簽通常以<%開頭以%>結束。 JSP是一種Java servlet&#xff0c;主要用于實現Java web應用程序的用戶界面部分。網頁開發者們通過結合HTML代碼、XHT…

Android gravity和layout_gravity的區別

一、gravity和layout_gravity相同處 兩者都是設置對齊方式的屬性。內部的屬性值相同。 根據英文意思也能理解其中的意思。如center_horizontal表示在水平方向上的位置為中間。 二、gravity和layout_gravity的不同處 gravity是設置自身內部元素的對齊方式。比如一個TextView&…

koa --- mongoose連接mongoDB

使用Mongoose對MongoDB進行操作 const mongoose require(mongoose); mongoose.connect(mongodb://localhost/test,{ })Mongoose中的Schema 定義Schema categorySchema const categorySchema new mongoose.Schema({name:String,description: String,createdAt:{type: Date,…

Java Web 請求轉發與請求重定向

Java Web 請求轉發與請求重定向 請求轉發 服務器行為&#xff0c;即用戶向服務器發送了一次http請求&#xff0c;該請求可能會經過多個信息資源處理以后菜返回給用戶&#xff0c;各個信息資源使用請求轉發機制互相轉發請求&#xff0c;但是用戶是感覺不到請求轉發的。通過req…

05.RDD詳解

05.Spark--RDD詳解 RDD詳解--groupByKey--reduceByKey [MapPartitionRDD單詞統計] 單詞統計 import org.apache.spark.{SparkConf,SparkContext} object WordCountScala{def main(args:Array[String]):Unit{//創建spark配置對象val confnew SparkConf()conf.setAppName("W…

Mininet

首先&#xff0c;我折騰了兩周多的東西終于弄出一點眉目了。 有以下幾個內容需要學習記憶一下。 1.虛擬機&#xff0c;弄不出來共享文件夾&#xff0c;就用U盤吧&#xff0c;賊快還不用安裝配置各種東西&#xff0c;virtualbox和VMware都支持。 2.ubantu安裝軟件中途失敗&#…

docker --- 使用docker-compose.yml生成redis,并連接redis-cli

docker.compose.yml 配置 version: 3.1 services:redis:image: redisports:- 6379:6379命令行:docker-compose up 查看: docker ps 進入redis-cli,輸入以下 docker exec -it 7dc0a redis-cli -h localhost -p 6379 操作Redis數據 設置 namemarron set name marron 獲取nam…

淺談javaweb三大框架和MVC設計模式

淺談javaweb三大框架和MVC設計模式轉載自&#xff1a;http://blog.csdn.net/sunpeng19960715/article/details/50890705 小序&#xff1a;博主以前在學javaweb的時候開始總不理解javaweb三大框架和MVC框架模式&#xff0c;雖然沒有把兩者混為一談&#xff0c;但是也是很暈菜。…

win下配置nginx

1.下載:http://nginx.org/en/download.html 2.在安裝目錄cmd: start nginx.exe 啟動nginx 3.修改默認運行端口80(nginx.conf): HTTP 數據分發 修改配置文件nginx.conf相應節點: 修改完后重啟服務: nginx -s reload TCP 數據分發: nginx 1.9以上版本支持tcp轉發 配置文件中增加:…

在springBoot中配置web.xml中配置的servlet

第一種 web.xml (截取的需要轉換的) 當攔截到 /socke t時執行該servlet <servlet><servlet-name>websocket</servlet-name><servlet-class>org.ldd.ssm.hangyu.socket.MyWebSocketServlet</servlet-class></servlet><servlet-mapping&g…

koa --- koa-bouncer驗證

使用 koa-bouncer中間件對傳入的數據進行驗證 const bouncer require(koa-bouncer); app.use(bouncer.middleware());const val async (ctx, next) > {ctx.validateBody(name).required(要求提供用戶名).isLength(6, 16, 用戶名長度應該為6~16).isString().trim()next();…

static關鍵字的作用

//C/C程序員面試指南 楊國祥等編著 定義全局靜態變量。全局靜態變量有以下特點&#xff1a; 在全局數據區分配內存&#xff1b;如果沒有初始化&#xff0c;其默認值為0&#xff1b;該變量在本文件內從定義開始到文件結束可見。定義局部靜態變量。局部靜態變量有以下特點&…

Redis 初次嘗試

Redis 初次嘗試 第一次接觸redis&#xff0c;也不知道要寫些什么。就玩了下將redis列表中的數據存入mysql數據庫中。 首先有三個文件&#xff1a; redis.php 添加數據進redis&#xff1b; insert_class.php 將數據插入數據庫&#xff1b; inert.php 調用insert_class.php;…

fiddler2抓包數據工具使用教程

一款免費且功能強大的數據包抓取軟件。它通過代理的方式獲取程序http通訊的數據&#xff0c;可以用其檢測網頁和服務器的交互情況&#xff0c;能夠記錄所有客戶端和服務器間的http請求&#xff0c;支持監視、設置斷點、甚至修改輸入輸出數據等功能。fiddler包含了一個強大的基于…

egg --- 初始化一個egg項目基本結構說明

Egg.js體驗 全局安裝 // 創建項目 $ npm i egg-init -g $ egg-init egg-example --typesimple $ cd egg-example $ npm i// 啟動項目 $ npm run dev $ open localhost:7000Egg.js的結構 路由(Router): 將請求URL和具體承擔執行動作的Controller的關系對應控制器(Controller)…

葫蘆娃

葫蘆娃救爺爺 1.隊名——代碼那些事兒 2.團隊成員 劉佳 211606320&#xff08;隊長&#xff09;李佳 211660313周世元 211606348王浩 211606378曾麗麗 211606302陳水蓮 211606303許燕婷 211606338楊小妮 2116063413.隊長博客鏈接 -https://www.cnblogs.com/LJ-D/p/9799944.html…

webstorm遇到的問題

問題一&#xff1a;英譯&#xff1a;未指定node.js的解釋器。 解決方法&#xff1a;將webstorm配置支持node.js并自動補全 步驟&#xff1a; 先下載node.jsFile->Setting->輸入Node.js&#xff08;選中點進去&#xff09;->Node imterpreter&#xff08;選擇node的安裝…

egg --- 配置連接mysql 創建模型 插入數據

在egg中使用egg-sequelize插件 sequelize是與數據庫操作相關的庫安裝: npm install --save egg-sequelize mysql2 在egg中配置sequelize 1.在 config/plugin.js中引入 egg-sequelize插件,代碼如下 sequelize: {enable: true,package: egg-sequelize }2.在config/config.def…

Flask 在 Debug 模式下初始化2次

請移步&#xff1a; http://blog.zengrong.net/post/2632.html https://stackoverflow.com/questions/9449101/how-to-stop-flask-from-initialising-twice-in-debug-mode/9476701#9476701 https://stackoverflow.com/questions/25504149/why-does-running-the-flask-dev-serve…

eclipse報錯: Could not generate secret

在調用微信接口時&#xff0c;出現一個錯誤&#xff1a; 一直以為是接口調用問題&#xff0c;經多方查詢和嘗試解決&#xff0c;最后找到根源&#xff1a; edit-->使用default就可以了。 原因&#xff1a; 在eclipse中運行時&#xff0c;把簽名信息給去掉了。 轉載于:https:…