数据库的操作无非就是增删改查
现在先看小程序中数据库增加操作
<button bindtap="add">添加数据</button>
<button bindtap="remove">删除数据</button>
<button bindtap="update">修改数据</button>
<button bindtap="find">查询数据</button>
<button bindtap="upload">上传图片</button>
增加数据
const db = wx.cloud.database();
add(){
db.collection('douban') //collection是数据集合
.add({
data:{ //不能进行批量添加 使用云函数方式进行批量添加
name: 'apple',
category: 'fruit',
price: 10,
}
}).then(res => {
console.log("res",res)
}).catch(err=>{
console.log("err",err)
})
},
注意点客户端只能添加一条数据;
删除数据
//删除操作
remove(){
db.collection('douban').doc('5e6ebf68efe8d765db7b66e6') //doc后面是放移除的id字段数据
.remove()
.then(res => {
console.log("res", res)
}).catch(err => {
console.log("err", err)
})
},
注意点 :
在这里有一个注意点,就是小成熟数据库删除只能删除你添加的选项,就是你数据库中有_openid这字段的数据,否则你是不能删除数据的。
之后的修改功能也一样
修改数据
db.collection('douban').doc('37e26adb5eb510d1004d4bee74d12799')
//.set({}) 替换更新
.update({ //局部更新
data: {
// price: _.inc(10) //_inc是价格增加10的意思
name: 'milk',
category: 'dairy'
}
}).then(res=>console.log(res))
.catch(err=>console.log(err))
查询功能
find(){
db.collection('douban')
.where({ //查询条件
price: _.gt(2) //查询指令 价格大于2的
})
.field({ //显示的字段
name: true,
price: true,
})
.orderBy('price', 'desc') //按照price进行降序排列 desc是降序排列 asc是升序排列
// .skip(1) 跳过一条
// .limit(10) 限制10条
.get()
.then(res=>console.log(res))
.catch(err=>console.log(err))
}
增删查改那些指令点击下方查询
小程序中的一些操作指令
附加
数据推送服务
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
db.collection('douban').where({}).watch({
onChange: (snapshot)=>{
console.log(snapshot.docChanges) //打印的是更改部分
},
onError:err=>{
console.log(err)
}
})
},
在onLoad函数中添加那段代码即可 跟react中订阅功能类似
//客户端进行订阅 store.subscribe(()=>{})
本文介绍了小程序中数据库的四个基本操作:增加数据、删除数据、修改数据和查询功能。在增加数据时,客户端只能添加一条;删除数据时,只能删除带有_openid字段的数据;修改数据需要注意权限;查询功能提供了数据库操作指令;此外,还讲解了如何实现数据推送服务,类似于React中的订阅功能。
2977

被折叠的 条评论
为什么被折叠?



