WeChat小程序开发(九、数据库的基本操作,云函数的初步了解)
笔记整理自b站课程 微信小程序云开发基础到实战 云数据库 云函数 云存储 云调用【新视觉】
具体更加详细的内容可查看微信官方文档-云开发-SDK文档
根据id查询数据库:
db.collection('datebaseName').doc('id').get({
...
})
这个id是区分记录的唯一标识符,一般是系统默认分配不用手动操作的。
使用数据库时经常会多次在获得的数据库记录后再次调用数据库,如果次数过多会形成 回调地狱。
db.collection('dbName').get({
success:res1=>{
db.collection('dbName').get({
success:res2=>{
db.collection('dbName').get({
....
})
}
})
}
})
//回调地狱
这里可以采用经过ES6 Promise封装过的方法解决:
db.collection('dbName').get().then(res1=>{
...
}).then(res2=>{}).catch(err={})
//then里的res就是上面的success中的res
//catch里的err就是fail里的err
形成链式结构更容易让人理清结构,也更容易书写。
promise中的其他封装方法有:
var a=e.detail.value.a var b=e.detail.value.b var c=e.detail.value.c //上面三行就等于下面的这一行 var {a,b,c}=e.detailo.value//封装后
关于删除数据库里的记录用remove方法:
//js里删除数据库的记录必须用dos db.collection('dbName').doc('id').remove().then(res=>{})
获取数据表中记录的个数:
db.collection('dbName').count().then(res=>{
...
})
监听数据表,数据表有变化会被监听
db.collection('dbName').watch({
onChange:res=>{
...
}
onErr:err=>{
...
}
})
限制传递的记录个数:
db.collection('dbName').where().limit(3).get().then(res=>{})
orderBy排序
db.collection('dbName').limit(3).orderBy('name','asc/desc').get().then(res=>{})
skip跳过前面前n条数据
db.collection('dbName').limit(3).skip(n).orderBy('name','asc').get().then(res=>{})
数据库中 command的使用
const db=wx.cloud.database() const _=db.command; db.collection('dbName') .where({ //hits:_.eq('abc')//等于 //hits:_.neq('abc')//不等于 //hit:_.lt(333)//筛选小于333的值 //hit:_.gte(333)//筛选大于等于333的值 //hit:_.in([255,666])//筛选数值为255或666的值 //hit:_.nin([255,666])//筛选数值不为255和666的值 }) .get() .then()
筛选某值为0-100的记录
db.collection('dbName')
.where({
hits:_and(_.gt(0),_lt(100))
})
.get()
.then()
表示满足hits=123并且name=abc的满足条件,可被选中
db.collection('dbName')
.where({
hits:123,
name:'abc'
})
.get()
.then()
针对数据表中多个属性的筛选操作:
db.collection('dbName')
.where({
_.or([
{
hit:_lt(300)
},
{
name:'abc'
}
])
})
//表示筛选满足hit:_lt(300)或者name:'abc'的记录
关于数值字段的查询
db.collection('dbName')
.where({
tabs:_.size(3)//筛选某数组属性的元素个数为n的记录
//tabs:_.all(['a','b'])筛选tabs(数组)里同时包含'a'.'b'的记录
})
.get()
.then()
关于update里的相关操作:
db.collection('dbName')
.updata({
data:{
hits:_.inc(n)//每次hits都自增n,n可正可负
//这是原子操作,即不会有进程并发问题
time:_remove()//删除time属性这项
style:{//原记录里没有style,可以这样直接增加这个属性
color:'red',
size:'12px'
}
tabs:_.push(['c'])//对tabs数组中增加为c的元素
tabs:_.pop(['c'])//删除tabs中为c的元素
tabs:_.unshift(['d'])//在数组最前面增加元素'd',即tabs[0]='d'
tabs:——.shift()//删除数组中的头元素。
tabs:_.pull('b')//移除tabs数组中值为b的元素
tabs:_.push({
each:['e'],//增加的元素为e
position:1//元素e的位置为下标1
})
}
})
.get()
.then()
以上的数据库操作代码都是写在前端的js文档中,但是实际操作时我们把数据库操作部分放在云函数里来处理,前端之处理逻辑部分,这样可以把前后端的作用清晰的分开而更有规划
对于云函数中处理数据库,其实大部分实质性的操作都和在前端处理没有区别:
//云函数Js文件 //云函数入门 const cloud=require('wx-server-sdk') cloud.init() const db=cloud.database() //云函数入口函数 exports.main = async(event,context)=>{ return await db.collection('dbName').get() //等待异步请求进行返回 } //云函数写完后一定要上传并部署云函数并且等待上传成功提示
//调入云函数的js文件 wx.cloud.callFunction({ name:'cloudFunctionName' }) .then(res=>{ console.log('success',res) })

浙公网安备 33010602011771号