微信小程序云开发使用方法-1
获取数据库
const db = wx.cloud.database()//调用默认云环境的数据库引用 const list = db.collection(list)//调取数据库集合
这里说明下: 1、db可以根据自己喜好来更改,我这里用的是文档上写的。 2、collection(‘list’)中的list是我们创建的数据集合的名称。
查询数据
.get() 查询单个数据或集合中多个数
db.collection("list").get({ success:res=>{ console.log(res) this.setData({ dataObj:res.data }) } })
.doc() 查询单个数据
db.collection(list).doc(单个数据的id).get().then(res => { // res.data 包含该记录的数据 console.log(res.data) })
.where()查询多个数据
db.collection("list").where({ name:"李四" }).get() .then(res=>{ this.setData({ dataObj:res.data }) console.log(res) })
ES6写法 then 回调
db.collection("list").get().then(res=>{ this.setData({ dataObj:res.data }) console.log(res) })
新增/插入数据
.add()方法 往集合中插入一条数据
addData(){ wx.showLoading({ title: 数据保存中, mask:true//提示框显示时,按钮不可点击 }) db.collection("list").add({ data:{ title:测试新增标题, name:"汪峰", content:"测试新增的内容", } }).then(res=>{ wx.hideLoading() console.log(res) }) },
实际操作表单提交到数据库
在form中添加bindsubmit 事件(触发submit事件),按钮中添加form-type,可用事件分别为:submit提交表单,reset重置表单。
<form action="" bindsubmit="addBtn"> <view> <input type="text" name="title" placeholder="请输入" class="ipt"></input> </view> <view> <input type="text" name="name" placeholder="请输入" class="ipt"></input> </view> <view> <textarea name="content" placeholder="请输入" class="ipt"></textarea> </view> <button type="primary" form-type="submit">提交</button> <button type="primary" form-type="reset">重置</button> </form>
//ES6写法 addBtn(res){ wx.showLoading({ title: 保存中, mask:true }) var resValue=res.detail.value db.collection("list").add({ data:resValue }).then(res=>{ wx.hideLoading() console.log(res) }) }
以上就是学习云开发数据库如何创建及引用,还有常用的插入、查询等知识。坚持每天学习新知识,后续持续更新!
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
原生微信小程序搭建