




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、數(shù)據(jù)持久化 -數(shù)據(jù)持久化 -回顧課堂目標(biāo)資源node.js中實(shí)現(xiàn)持久化的多種方法文件系統(tǒng)數(shù)據(jù)庫安裝、配置node.js原生驅(qū)動(dòng)Node.js ORM - Sequelize購物車相關(guān)接口實(shí)現(xiàn)回顧模塊系統(tǒng)全局變量API課堂目標(biāo)掌握node.js中實(shí)現(xiàn)持久化的多種方法掌握、安裝和配置掌握node.js中原生驅(qū)動(dòng)模塊的應(yīng)用掌握node.js中的OR 模塊Sequelize的應(yīng)用實(shí)現(xiàn)商城案例中所需接口資源相關(guān):node驅(qū)動(dòng):文檔 Sequelize:文檔、apimongodb相關(guān):MongoDB: node驅(qū)動(dòng):文檔 mongoose:文檔redis相關(guān):redis: node_redis:文檔nod
2、e.js中實(shí)現(xiàn)持久化的多種方法文件系統(tǒng) fs數(shù)據(jù)庫關(guān)系型數(shù)據(jù)庫-文檔型數(shù)據(jù)庫-mongodb鍵值對(duì)數(shù)據(jù)庫-redis文件系統(tǒng)數(shù)據(jù)庫/ 實(shí)現(xiàn)一個(gè)文件系統(tǒng)讀寫數(shù)據(jù)庫const fs = require(fs);function get(key) fs.readFile(./db.json, (err, data) = const json = JSON.parse(data); console.log(jsonkey););function set(key, value) fs.readFile(./db.json, (err, data) = / 可能是空文件,則設(shè)置為空對(duì)象const json
3、 = data ? JSON.parse(data) : ; jsonkey = value; / 設(shè)置值/ 重新寫入文件fs.writeFile(./db.json, JSON.stringify(json), err = if (err) console.log(err);console.log(寫入成功!);););/ 命令行接口部分const readline = require(readline); const rl = readline.createerface(input: pros.stdin,output: pros.stdout);rl.on(line, function(
4、input) const op, key, value = input.split( );if (op = get) get(key) else if (op = set) set(key, value) else if(op = quit) rl.close();else console.log(沒有該操作););rl.on(close, function() console.log(程序結(jié)束);pro);s.exit(0);安裝、配置macwindowsnode.js原生驅(qū)動(dòng)安裝模塊: npm i模塊基本使用-saveconst= require();/ 連接配置const cfg = h
5、ost: localhost, user: root,password: admin, / 修改為你的database: kaikeba / 請(qǐng)確保數(shù)據(jù)庫存在;/ 創(chuàng)建連接對(duì)象const conn =.createConnection(cfg);/ 連接conn.connect(err = if (err) throw err; else console.log(連接成功!););/ 查詢 conn.query()/ 創(chuàng)建表const CREATE_SQL = CREATE TABLE IF NOT EXISTS test (idNOT NULL AUTO_INCREMENT,Node.js
6、ORM - Sequelize概述:基于Promise的ORM(Object Relation Map),支持多種數(shù)據(jù) 、事務(wù)、關(guān)聯(lián)等安裝: npm i sequelize基本使用:2 -Sconst Sequelize = require(sequelize);/ 建立連接const sequelize = new Sequelize(kaikeba, root, admin, host: localhost,dialect: , operatorsAliases: false);/ 定義模型const Fruit = sequelize.define(Fruit, name: type:
7、Sequelize.STRING(20), allowNull: false , price: type: Sequelize.FLOAT, allowNull: false , stock: type: Sequelize.EGER, defaultValue: 0 );/ 同步數(shù)據(jù)庫,force: true則會(huì)刪除已存在表 Fruit.sync().then() = / 添加測(cè)試數(shù)據(jù)return Fruit.create( name: 香蕉,message VARCHAR(45) NULL, PRIMARY KEY (id);const INSERT_SQL = INSERTO test(
8、message) VALUES(?); const SELECT_SQL = SELECT * FROM test; conn.query(CREATE_SQL, err = if (err) throw err;/數(shù)據(jù)conn.query(INSERT_SQL, o,world, (err, result) = if (err) throw err;console.log(result); conn.query(SELECT_SQL, (err, results) = console.log(results);conn.end(); / 若query語句有嵌套,則end需在此執(zhí)行););強(qiáng)制
9、同步:創(chuàng)建表之前先刪除已存在的表Fruit.sync(force: true)避免自動(dòng)生成時(shí)間戳字段指定表名: freezeTableName: true 或 tableName:設(shè)置前者則以mName作為表名;設(shè)置后者則按其值作為表名。Getters & Setters:可用于定義偽屬性或到數(shù)據(jù)庫字段的保護(hù)屬性/ 定義為屬性的一部分name: type: Sequelize.STRING, allowNull: false,get() const fname = this.getDataValue(name); const price = this.getDataValue(price);
10、const stock = this.getDataValue(stock);return $fname(價(jià)格: $price 庫存:$stockkg);/ 定義為模型選項(xiàng)getterMethods: amount()return this.getDataValue(stock) + kg;,setterMethods: amount(val)const idx = val.indexOf(kg); const v = val.slice(0, idx); this.setDataValue(stock, v);const Fruit = sequelize.define(Fruit, , t
11、imests: false);price: 3.5);).then() = / 查詢Fruit.findAll().then(fruits = console.log(JSON.stringify(fruits);););校驗(yàn):可以通過校驗(yàn)功能驗(yàn)證模型字段格式、內(nèi)容,校驗(yàn)會(huì)在 create 、 update 和 save 時(shí)自動(dòng)運(yùn)行模型擴(kuò)展:可添加模型實(shí)例方法或類方法擴(kuò)展模型數(shù)據(jù)查詢/ 通過id查詢Fruit.findById(1).then(fruit = / fruit是一個(gè)Fruit實(shí)例,若沒有則為null/ 添加類級(jí)別方法Fruit.classify = function(name)
12、const tropicFruits = 香蕉, 芒果, 椰子; / 熱帶水果return tropicFruits.includes(name) ? 熱帶水果:其他水果;/ 添加實(shí)例級(jí)別方法Ftotype.totalPrice = function(count) return (this.price * count).toFixed(2);/ 使用類方法香蕉,草莓.forEach(f = console.log(f+是+Fruit.classify(f);/ 使用實(shí)例方法Fruit.findAll().then(fruits = const f1 = fruits;conso
13、le.log(買5kg$需要¥$f1.totalPrice(5););price: validate: isFloat: msg: 價(jià)格字段請(qǐng)輸入數(shù)字 ,min: args: 0, msg: 價(jià)格字段必須大于0 ,stock: validate: isNumeric: msg: 庫存字段請(qǐng)輸入數(shù)字 / 通過模型實(shí)例觸發(fā)setterMethods Fruit.findAll().then(fruits = console.log(JSON.stringify(fruits);/ 修改amount,觸發(fā)setterMethods fruits0.amount = 150kg; fru
14、its0.save(););console.log(fruit.get(););/ 通過屬性查詢Fruit.findOne( where: name: 香蕉 ).then(fruit = / fruit是首個(gè)匹配項(xiàng),若沒有則為nullconsole.log(fruit.get(););/ 獲取數(shù)據(jù)和總條數(shù)Fruit.findAndCountAll().then(result = console.log(result.count); console.log(result.rows.length););/ 查詢操作符const Op = Sequelize.Op; Fruit.findAll(/
15、where: price: Op.lt:4 , stock:where: price: Op.lt:4,Op.gt:2 ).then(fruits = console.log(fruits.length);); Op.gte: 100 / 或語句Fruit.findAll(/ where: Op.or:price: Op.lt:4, stock: Op.gte:100where: price: Op.or:Op.gt:3).then(fruits = console.log(fruits0.get(););,Op.lt:2/ 分頁Fruit.findAll( offset: 0,limit:
16、2,)/ 排序Fruit.findAll(order: price, DESC,)/ 聚合setTimeout() = Fruit.max(price).then(max = n console.log(max, max););Fruit.sum(price).then(sum = console.log(sum, sum););, 500);更新Fruit.findById(1).then(fruit = / 方式1 fruit.price = 4;fruit.save().then()=console.log(update!););/ 方式2Fruit.update(price:4, wh
17、ere:id:1).then(r = console.log(r);console.log(update!)刪除關(guān)聯(lián)視時(shí)間而定,充裕則講,不夠則在項(xiàng)目期帶出/ 1:N關(guān)系const Player = sequelize.define(player, name: Sequelize.STRING); const Team = sequelize.define(team, name: Sequelize.STRING);/ 會(huì)添加teamId到Player表作為外鍵 Player.belongsTo(Team); / 1端建立關(guān)系 Team.hasMany(Player); / N端建立關(guān)系/ 同
18、步sequelize.sync(force:true).then(async ()= await Team.create(name: 火箭);await Player.bulkCreate(name: , teamId:1,name: , teamId:1);/ 1端關(guān)聯(lián)查詢const players = await Player.findAll(include:Team); console.log(JSON.stringify(players,null,t);/ N端關(guān)聯(lián)查詢const team = await Team.findOne(where:name:火箭,include:Player);console.log(JSON.string
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 云南工程職業(yè)學(xué)院《重金屬冶金學(xué)》2023-2024學(xué)年第二學(xué)期期末試卷
- 新疆應(yīng)用職業(yè)技術(shù)學(xué)院《外國戲劇史》2023-2024學(xué)年第二學(xué)期期末試卷
- 2025屆河南省駐馬店市驛城區(qū)高三上學(xué)期一模歷史試卷
- 黑龍江職業(yè)學(xué)院《勞動(dòng)定額學(xué)》2023-2024學(xué)年第二學(xué)期期末試卷
- 2024-2025學(xué)年浙江省部分重點(diǎn)高中高二上學(xué)期12月月考?xì)v史試卷
- 九江學(xué)院《文具設(shè)計(jì)》2023-2024學(xué)年第二學(xué)期期末試卷
- 青海師范大學(xué)《汽車電子電氣A》2023-2024學(xué)年第二學(xué)期期末試卷
- 煙臺(tái)理工學(xué)院《中國古代文學(xué)作品》2023-2024學(xué)年第二學(xué)期期末試卷
- 南陽農(nóng)業(yè)職業(yè)學(xué)院《就業(yè)與創(chuàng)業(yè)教育》2023-2024學(xué)年第二學(xué)期期末試卷
- 桂林信息工程職業(yè)學(xué)院《生物質(zhì)能源概論》2023-2024學(xué)年第二學(xué)期期末試卷
- ESD技術(shù)要求和測(cè)試方法
- 正確認(rèn)識(shí)民族與宗教的關(guān)系堅(jiān)持教育與宗教相分離
- 宜黃縣二都鎮(zhèn)高山飾面用花崗巖開采以及深加工項(xiàng)目環(huán)評(píng)報(bào)告
- 血液科護(hù)士的惡性腫瘤護(hù)理
- 畜禽廢棄物資源化利用講稿課件
- 土地糾紛調(diào)解簡單協(xié)議書
- 服裝倉庫管理制度及流程
- 《餐飲渠道開發(fā)方案》課件
- 架子工安全教育培訓(xùn)試題(附答案)
- 一中師德考核評(píng)估制度
- 春節(jié)習(xí)俗中的傳統(tǒng)茶文化與茶藝
評(píng)論
0/150
提交評(píng)論