开课吧web全栈架构师第16期2020完结04数据持久化mysql_第1页
开课吧web全栈架构师第16期2020完结04数据持久化mysql_第2页
开课吧web全栈架构师第16期2020完结04数据持久化mysql_第3页
开课吧web全栈架构师第16期2020完结04数据持久化mysql_第4页
开课吧web全栈架构师第16期2020完结04数据持久化mysql_第5页
已阅读5页,还剩12页未读, 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

MongoDB:node驱动:文档//constfs=functionget(key){fs.readFile("./db.json",(err,data)=>{constjson=JSON.parse(data);}functionset(key,{fs.readFile("./db.json",(err,data){constjsondataJSON.parse(data)json[key]=value;//设置值fs.writeFile("./db.json",JSON.stringify(json),err{if(err){}}constreadline=require("readline");constrl=readline.createInterface({input:process.stdin,output:rl.on("line",function(input)const[op,key,value]=input.split("if(op==={}elseif(op==={set(key,}elseif(op==='quit'){rl.close();}else}rl.on("close"functionMySQL菜鸟 /mysql/mysql-node.js安装mysqlnpmimysql////constmysql=constcfg=host:"localhost",user:"root",password"example"database"kaikeba"constconn=//连接conn.connect(err=>{if(err){throw}else}查询constCREATE_SQL=`CREATETABLEIFNOTEXISTStestidINTNOTNULLmessageVARCHAR(45)NULL,PRIMARYKEY(id))`;constconstINSERT_SQL=`INSERTINTOtest(message)VALUES(?)`;constSELECT_SQL=`SELECT*FROMtest`;conn.query(CREATE_SQL,err=>{if{throw}conn.query(INSERT_SQL, o,world",(err,result){if(err){throw}conn.query(SELECT_SQL,(err,results)=>{conn.end若query语句有嵌套,则end//mysql2.js//mysql2.js(async()=>//getconstmysql=constcfg=host:"localhost",user:"root",password"example"database"kaikeba"//createtheconstconnection=await查询constCREATE_SQL=`CREATETABLEIFNOTEXISTStestidINTNOTNULLmessageVARCHAR(45)NULL,PRIMARYKEY(id))`;constINSERT_SQL=`INSERTINTOtest(message)constSELECT_SQL=`SELECT*FROM//queryletret=awaitconsoleconsole.log('create:',ret=awaitconnection.execute(INSERT_SQL,['abc']);console.log('insert:',ret)const[rows,fields]=awaitconsole.log('select:',Node.jsORM-概述:基于Promise的ORM(ObjectRelationMap),是一种数据库中间件支持多种数据库、npmisequelizemysql2((async()=>constSequelize=constsequelize=newSequelize("kaikeba","root",{host:"localhost",dialect:"mysql",operatorsAliases:false仍可通过传入operatorsmapconstFruit=sequelize.define("Fruit",name:{type:Sequelize.STRING(20),allowNull:false},price:{type:Sequelize.FLOAT,allowNull:false},stock:{type:Sequelize.INTEGER,defaultValue:0}trueletret=awaitFruit.sync()ret=Fruit.create({name:price3.5ret=awaitFruit.findAll()awaitawait{price:4wherename:'香蕉')constOp=Sequelize.Op;ret=await//where:{price:{[Op.lt]:4},stock:{[Op.gte]:100}where:{price:{[Op.lt]:4,[Op.gt]:2}console.log('findAll',JSON.stringify(ret,'',:constconstFruit=sequelize.define("Fruit",{timestamps: zeTableName:true蛇形命名underscored:true,id:id:type:Sequelize.DataTypes.UUID,defaultValue:Sequelize.DataTypes.UUIDV1,primaryKey:name:type:allowNullallowNull:false,get(){constfname=this.getDataValue("name");constprice=this.getDataValue("price");conststock=return`${fname}(价格:¥${price}}options{returnthis.getDataValue("stock")+}constidx=val.indexOf('kg');constv=val.slice(0,idx);this.setDataValue('stock',v);}}}//通过模型实例触发setterMethodsFruit.findAll().then(fruits{修改amount,触发setterMethodsfruits[0].amount='150kg';校验:可以通过校验功能验证模型字段格式、内容,校验会在createupdate和save时自动priceprice:validate:isFloatmsg"价格字段请输入数字"minargs0msg"价格字段必须大于0"}stock:validate:isNumericmsg:"库存字段请输入数字"}}Fruit.classify=function(name)consttropicFruits['香蕉''芒果''椰子'returntropicFruits.includes(name'热带水果':'其他水果Ftotype.totalPrice={return(this.price*['香蕉','草莓'].forEach(fconsole.log(f+'是{const[f1]=通过id查询(不支持了Fruit.findById(1).then(fruit=>fruit是一个Fruit实例,若没有则为nullFruit.findOnewherename"香蕉"then(fruitfruit是首个匹配项,若没有则为nullFruit.findOne({attributes:['name']}).then(fruit=>fruit是首个匹配项,若没有则为null{console.log(result.count);constOp=Sequelize.Op;//where:{price:{[Op.lt]:4},stock:{[Op.gte]:100}where:{price:{[Op.lt]:4,[Op.gt]:2}).then(fruits{//where:{[Op.or]:[{price:{[Op.lt]:4}},{stock:{[Op.gte]:}}]where:{price:{[Op.or]:[{[Op.gt]:3},{[Op.lt]:2}).then(fruits{//分页t:limit://排序order:[['price',{console.log("max",{console.log("sum",FruitFruit.findById(1).then(fruit=>//方式1fruit.price4;方式Fruit.update({price:4},{where:{id:1}}).then(r{console.log(r);方式Fruit.findOne({where:{id:1}}).then(r=>方式Fruit.destroy({where:{id:1}}).then(r=>实体关系图和与域模型constconstsequelize=require('./util/database');constProduct=require('./models/product');constUser=require('./models/user');constCart=constCartItem=require('./models/cart-item');constOrder=require('./models/order');constOrderItem=require('./models/order-Product.belongsTo(User,{constraints:true,onDelete:'CASCADE'Cart.belongsToMany(Product,{through:{through:Order.belongsToMany(Product,{through:{through:ncresult=>{letuser=awaitUser.findByPk(1)if(!user){user=User.create({name::await}'app.listen(3000,()=>console.log("Listeningtoportappapp.use(async(ctx,next)=>constuser=awaitUser.findByPk(1)ctx.user=user;awaitconstrouter=require('koa-*router.get('/admin/products',async(ctx,next)=>//constproducts=awaitctx.user.getProducts()constproducts=awaitProduct.findAll()ctx.body={prods:products}*router.post('/admin/product',asyncctx{constbody=constres=awaitctx.user.createProduct(body)ctx.body={success:true}*router.delete('/admin/product/:id',async(ctx,next){constid=ctx.params.idconstres=awaitProduct.destroy({where:{}ctx.body={success:true*router.get('/cart',asyncctx=>constcart=awaitctx.user.getCart()constproducts=awaitcart.getProducts()ctx.body={products}*router.post('/cart',asyncctx{const{body}=ctx.requestconstprodId=body.idletnewQty=constcart=awaitctx.user.getCart()constproducts=awaitcart.getProducts({where:id:}letif(products.length>{product=}if(product)constoldQty=product.cartItem.tynewQty=oldQty+1}elseproduct=await}await{through:ty:}ctx.body={success:true*router.post('/orders',asyncctx{constcart=awai

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论