




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
1、數(shù)據(jù)持久化 -數(shù)據(jù)持久化 -回顧課堂目標(biāo)資源node.js中實現(xiàn)持久化的多種方法文件系統(tǒng)數(shù)據(jù)庫安裝、配置node.js原生驅(qū)動Node.js ORM - Sequelize購物車相關(guān)接口實現(xiàn)回顧模塊系統(tǒng)全局變量API課堂目標(biāo)掌握node.js中實現(xiàn)持久化的多種方法掌握、安裝和配置掌握node.js中原生驅(qū)動模塊的應(yīng)用掌握node.js中的OR 模塊Sequelize的應(yīng)用實現(xiàn)商城案例中所需接口資源相關(guān):node驅(qū)動:文檔 Sequelize:文檔、apimongodb相關(guān):MongoDB: node驅(qū)動:文檔 mongoose:文檔redis相關(guān):redis: node_redis:文檔nod
2、e.js中實現(xiàn)持久化的多種方法文件系統(tǒng) fs數(shù)據(jù)庫關(guān)系型數(shù)據(jù)庫-文檔型數(shù)據(jù)庫-mongodb鍵值對數(shù)據(jù)庫-redis文件系統(tǒng)數(shù)據(jù)庫/ 實現(xiàn)一個文件系統(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è)置為空對象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ū)動安裝模塊: npm i模塊基本使用-saveconst= require();/ 連接配置const cfg = h
5、ost: localhost, user: root,password: admin, / 修改為你的database: kaikeba / 請確保數(shù)據(jù)庫存在;/ 創(chuàng)建連接對象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則會刪除已存在表 Fruit.sync().then() = / 添加測試數(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í)行););強制
9、同步:創(chuàng)建表之前先刪除已存在的表Fruit.sync(force: true)避免自動生成時間戳字段指定表名: 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(價格: $price 庫存:$stockkg);/ 定義為模型選項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);););校驗:可以通過校驗功能驗證模型字段格式、內(nèi)容,校驗會在 create 、 update 和 save 時自動運行模型擴(kuò)展:可添加模型實例方法或類方法擴(kuò)展模型數(shù)據(jù)查詢/ 通過id查詢Fruit.findById(1).then(fruit = / fruit是一個Fruit實例,若沒有則為null/ 添加類級別方法Fruit.classify = function(name)
12、const tropicFruits = 香蕉, 芒果, 椰子; / 熱帶水果return tropicFruits.includes(name) ? 熱帶水果:其他水果;/ 添加實例級別方法Ftotype.totalPrice = function(count) return (this.price * count).toFixed(2);/ 使用類方法香蕉,草莓.forEach(f = console.log(f+是+Fruit.classify(f);/ 使用實例方法Fruit.findAll().then(fruits = const f1 = fruits;conso
13、le.log(買5kg$需要¥$f1.totalPrice(5););price: validate: isFloat: msg: 價格字段請輸入數(shù)字 ,min: args: 0, msg: 價格字段必須大于0 ,stock: validate: isNumeric: msg: 庫存字段請輸入數(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是首個匹配項,若沒有則為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)視時間而定,充裕則講,不夠則在項目期帶出/ 1:N關(guān)系const Player = sequelize.define(player, name: Sequelize.STRING); const Team = sequelize.define(team, name: Sequelize.STRING);/ 會添加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等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 農(nóng)業(yè)生物多樣性生物技術(shù)考核試卷
- 火力發(fā)電廠安全生產(chǎn)與應(yīng)急預(yù)案考核試卷
- 微生物檢驗實驗設(shè)計應(yīng)該考慮的因素試題及答案
- 2025年【機(jī)修鉗工(技師)】模擬考試題及答案
- 消費金融資產(chǎn)質(zhì)量管理與催收策略考核試卷
- 玩具制造業(yè)的綠色制造挑戰(zhàn)考核試卷
- 煉油廠設(shè)備安裝與調(diào)試的技術(shù)要求考核試卷
- 項目決策工具與技術(shù)的運用考核試題及答案
- 磷肥生產(chǎn)過程中的工藝安全評價考核試卷
- 電動機(jī)制造中的電機(jī)繞組技術(shù)創(chuàng)新考核試卷
- SAP軟件FICO模塊常用增強之一:固定資產(chǎn)的屏幕增強
- 醫(yī)院門診登記本
- 如愿二聲部合唱簡譜文檔
- GB/T 1531-2020銅及銅合金毛細(xì)管
- GB/T 12785-2002潛水電泵試驗方法
- 機(jī)械制圖國家標(biāo)準(zhǔn)
- 汽車吊起重吊裝方案-
- 陰囊疾病超聲診斷課件
- 信息資產(chǎn)及分級管理程序
- 信用修復(fù)授權(quán)委托書
- 危大工程驗收記錄表(腳手架工程)
評論
0/150
提交評論