1.初始化
1.1个人小程序开发说明
-
一个邮箱只能注册一个小程序
-
一个身份证可以注册5个,个人小程序
1.2查看云开发ID
1.3始化云开发环境(重要)
- 初始化填入我们的环境ID,以初始化我们的开发环境
2.操作云数据库
2.1创建集合和获取数据库
-
随后在js文件中获取db
const db = wx.cloud.database() //进一步获取一个集合 const users=db.collection('users') Page({...}) //如果要获取特定数据库 const testDB = wx.cloud.database({ env: 'test' //加入环境名 })
2.2基本操作(代码实现)
整体代码
(关于promise语法详见另一篇博客)
入口:
-
wxml
<view> 姓名:<input bindinput='changename' /> 城市:<input bindinput='changecity' /> <button type="primary" style="width:85%" bindtap="insert">添加</button> </view> <view type='text'> <button type="primary" style="width:85%" bindtap="select">查询(只需要输入名,查看控制台)</button> <button type="warn" style="width:85%" bindtap="delete">删除(只需要输入名字)</button> <button type="primary" style="width:85%" bindtap="update">更新</button> </view>
-
js文件
// pages/coludfunction/coludfunction.js //引入数据库 const db=wx.cloud.database() Page({ data: { name:'', city:'' }, //更新数据操作 changename(e){ this.setData({ name:e.detail.value }) }, changecity(e){ this.setData({ city:e.detail.value }) }, //插入数据操作 insert(e){ db.collection('users').add({//向数据库添加数据 data:{ city:this.data.city, name:this.data.name, due:db.serverDate(), //服务器时间 //结束时间设置为一小时后 //due: db.serverDate({ // offset: 60 * 60 * 1000 // }) }, success:function(res){ console.log('添加成功') }, }) }, //获取get()使用promise语法 select(e){ const that=this db.collection('users'). where({//where子句可以没有 name:that.data.name }) .get() .then(res=>{ console.log('结果',res.data) }) .catch(err=>{ console.log('请求失败',err) }) }, //delete delete(e){ const that=this db.collection('users') .where({//where子句可以没有 name:that.data.name }) .remove() .then(res=>{ console.log('删除成功',res) }) .catch(res=>{ console.error('删除失败',err) }) }, //更新 update(e){ const that=this wx.cloud.database().collection('users') .where({ name:that.data.name }) .update({ data:{ city:that.data.city } }) .then(res=>{ console.log('修改成功',res) }) .catch(err=>{ console.error('修改失败',err) }) } })
效果
2.2.1get()查询
-
where().get()where子句添加条件
//获取get()使用promise语法 select(e){ const that=this db.collection('users'). where({//where子句可以没有 name:that.data.name }) .get() .then(res=>{ console.log(res.data) }) .catch(err=>{ console.log('请求失败',err) }) },
-
doc(),里面用到的参数是我们数据里的_id字段
//获取get()使用promise语法 select(e){ const that=this db.collection('users'). .doc('') .get() .then(res=>{ console.log(res.data) }) .catch(err=>{ console.log('请求失败',err) }) },
2.2.2add()添加
2.2.3remove()删除
2.2.4update()更新
- 修改成功
2.3权限管理
- 仅创建者可读写(普通用户无法读取)
- 可以看到每个数据库的权限都不一样
资料说明:
-
内容来源于微信小程序开发文档(个体文档方便自己开发回忆)
-
本文需要一定的小程序开发经验