微信小程序云开发【数据库连接与查询】
笔记-2020-07-27 方法1
1.前端页面绑定一个事件 getData
<button type="primary" bindtap="getData">点击获取数据</button>
2.在js文件中写getData函数,测试是否绑定成功
getData(){
console.log(1111);
}
3.在js文件定义一个变量db 连接总体的数据库
const db=wx.cloud.database()
4.在getData方法中调用db,连接我们名字为“demolist”的数据库,并且用get方法获取数据,在get中写一个对象,对象中写一个回调函数,打印当前对象,控制台查看数据是否有打印
getData(){
// 获取相应名字的数据库 用get获取该数据库的数据 回调函数
db.collection("demolist").get({
success:res=>{
console.log(res)
}
})
},
5.对象里有回调函数,.doc用来传递数据库的独有id参数,写在数据库名字和get方法的中间
6.在data数据段中定义一个空的变量 dataObj
dataObj:""
7.在 getData方法中调用this.setData方法给dataObj赋值
getData(){
// 获取相应名字的数据库 用get获取该数据库的数据 回调函数
db.collection("demolist").get({
success:res=>{
this.setData({
dataObj:res.data
})
}
})
},
8.如果demolist中有多条数据,则得到的dataObj为数组,在前端可以用用for循环调用,dataObj每一项为对象类型
<view wx:for="{
{dataObj}}">{
{
item.author}}-{
{
item.title}}</view>
方法2(then(),常用方法)
1.可以在get方法后面写一个.then()函数,
db.collection("demolist").get().then(res=>{
})
db.collection("demolist").get().then(res=>{
console.log(res);
this.setData({
dataObj:res.data
})
})
在then()里面写 res箭头函数 then就是一个回调,可以理解为success的相同用法,将请求到的东西返回给res
拓展:(then可以写很多个,以链式存在,then返回正确的结果,而catch返回错误的结果通常用来console.log(err),打印错误)
db.collection("demolist").get()
.then(res=>{
console.log(res);
})
.where写在get前面(也就是和doc相同的位置) .where方法里面要写一个对象
// 查询
db.collection("demolist").where({
author:"陈奕海"
}).get()
.then(res=>{
console.log(res);
})
上一篇:
IDEA上Java项目控制台中文乱码
