数据库
使用
collection
- 初始化
const db=wx.cloud.database()
- 连接数据库
db.collection('demouser')
//demouser为表名
获取所有记录的示例:
db.collection('demouser').get({
success:res=>{
console.log(res)
}
})
查询get
获取所有元素后可通过wx:for循环渲染
db.collection('demouser').get({
success:res=>{
//console.log(res)
this.setData({
user:res.data
})
console.log(this.data.user)
}
})
//获取所有元素,并将其中的data给user数组
通过id查询:通过**.doc**方法,.doc只能方id
db.collection('demouser').doc('d4107ab1624ec8310593163d1d6415ba').get({
success:res=>{
this.setData({
user:res.data
})
console.log(this.data.user)
}
})
promies化的方法进行处理回调函数可以防止回调地狱(.then或.catch的链式方法)
db.collection('demouser').get().then(res=>{
this.setData({
user:res.data
})
console.log(this.data.user)
})
用where进行条件筛选
db.collection('demouser').where({
identity:1
}).get().then(res=>{
this.setData({
user:res.data
})
console.log(this.data.user)
})
插入add
db.collection('demouser').add({
data:{
name:this.data.name,
age:this.data.age,
identity:this.data.identity
}
}).then(res=>{
console.log(res)
})
在插入数据时,可以添加节流操作
简单的节流操作可在可在showLoading中加入mask属性。
wx.showLoading({
title: '数据添加中。。。',
mask:true
})
更新updata和set,删除remove
对于更新操作和删除操作,小程序端仅可以通过.doc的id属性进行更新或删除,.where需要在云函数进行实现。
在小程序端,对于updata,set,remove,仅在所以有用户可读,仅创建者可读写和仅创建者可读写两种权限下使用。
计数count
count的效率高于get,因为其只获得数量
数据库监听watch
watch文档
目前实验结果:在小程序端,无论watch定义在什么地方,只要数据发生变化都会被调用。
例如:有监听函数datawatcher
dataWatcher(){
db.collection('demouser').watch({
onChange:res=>{
console.log(res)
console.log(res.docChanges)
console.log('数据监听触发')
this.setData({
allitem:res.docs
})
this.count_test()
},
onError:err=>{
console.log(err)
}
})
},
不论其在什么地方被调用,如onLoad,onPullDownRefresh或自己定义的监听函数中,只要数据库中的数据发生了变化,就会被调用。但是若只定义datawatcher,却不对其进行调用,则不会起效。
构建查询条件
- where:条件查询
- orderBy:排序
- limit+skip:可以实现分页操作
- field:传入一个对象,给出需要查出的属性,可提高查询效率
command
初始化
const _=db.command
and,or对于多条属性同时操作
多属性同时操作时,使用数组[],其中元素为对象{},对象中包含属性。以实现对多属性查询
云函数
添加云函数
新建云函数
右键cloudfunctions,选择新建Node.js新建一个云函数,云函数编写完或更改后,需要上传并部署。
云函数中需要初始化
const db=cloud.database()
调用云函数
wx.cloud.callFunction({
name:'getData'
}).then(res=>{
console.log(res)
})
promies
await:等待异步请求完成