学习资料
学习笔记:https://xiaoshitou.blog.csdn.net/article/details/112391688?spm=1001.2014.3001.5502
云开发启动
app.js中的 onLaunch 函数中初始化
wx.cloud.init({
env: 'cloud1-5gc3ghfz919f82d3' //云开发环境id
})
云开发文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/quick-start/miniprogram.html
数据库基础
在云开发中选择数据库
创建一个集合,只能是英文或数字,不能是汉字
初始化
const db = wx.cloud.database()
1. 查询操作—get()
// 传统数据
db.collection('goods').get({
// 请求成功
success(res) {
console.log('请求成功',res);
},
fail(err) {
console.log('请求失败', err);
}
})
// ES6 的简洁语法
db.collection('goods').get().then(res => {
console.log('第二种请求成功', res);
}).catch(err => {
console.log('请求失败', err);
})
传统写法中的this 指向的是当前函数,而箭头函数的 this 指向的pages
1.1 查询条件–where()
db.collection('goods').where({
name: '苹果'
})
.get().then(res => {
this.setData({
list: res.data
})
console.log('第二种请求成功', res.data);
}).catch(err => {
console.log('请求失败', err);
})
1.2 单条查询–doc()
获取一个记录的数据,doc参数不能为空,参数为一个id值
db.collection('goods').doc('d2fe6f20624ee579058c4bea0e74ab35')
.get()
.then(res => {
console.log('查询单条成功', res.data);
this.setData({
good: res.data
})
})
.catch(err => {
console.log('查询失败', err);
})
2. 数据库权限
数据库 -> 数据权限
- 仅创建者可读写:管理员创建了这条数据,普通用户读取不到
- 所有用户可读:不管谁创建的数据,所有人都可以读
3. 添加数据–add
const db = wx.cloud.database()
db.collection('goods')
.add({ // 添加数据
data: {
name: '车厘子',
price: '200'
}
})
.then(res => {
console.log('添加成功', res);
})
.catch(err => {
console.log('添加失败', err);
})
4. 更新数据–update()
修改数据库中存在的数据
修改数据必须给定修改条件可以用 where 或者 doc 来指定要修改的对象
wx.cloud.database().collection('goods')
.where({
name: '车厘子'
})
.update({
data: {
price: 100
}
})
.then(res => {
console.log('修改成功', res);
})
.catch(err => {
console.error('修改失败', err);
})
5. 删除数据–update()
删除数据,结合 doc 删除单条数据
wx.cloud.database().collection('goods')
.doc('d2fe6f20624fdedb05c201a1430f2a76') // 填写要删除条件的 _id
.remove() // 删除数据
.then(res => {
console.log('删除成功', res);
})
.catch(err => {
console.error('删除失败', err);
})
配合 wx.showModel() API 使用,进行删除前的确认
wx.showModal({
title: