微信云开发数据库增删改查
数据库的增删改查
增
注意 data内值格式应为: name:this.data.name,
使用setdata只是为了对前端做一遍更新
const db=wx.cloud.database()
const _=db.commond
var that=this
db.collection("bank").add({
data: {
databaseValueName:VarInYourProgram,
},
success:function(res){
wx.showToast({
title:"添加成功",
duration:2000
})
that.setData({
databaseValueName:VarInYourProgram,
})
},
fail:function(res){
wx.showToast({
title:"添加失败",
duration:2000
})
}
})
删
goodId是数据库待删除记录的_id值
const db=wx.cloud.database()
const _=db.commond
var that=this
db.collection("bank").doc(goodId).remove({
success:function(res){
wx.showToast({
title:"删除成功",
duration:2000
})
},
fail:function(res){
wx.showToast({
title:"删除失败",
duration:2000
})
}
})
如果前端使用<form wx:for("{{datas}}")>,可以使用前端返回的index来查找_id值
例如:
前端:(goods为data保存的数据库的值,goodName是一个属性)
<form bindsubmit="action" wx:for="{{goods}}" wx:for-index="index" wx:for-item="item" wx:key="{{item.goodName}}">
<input hidden='true' name='index' value={{index}}>
<button form-type='submit'> submit</button>
</form>
后端:
这样就获得了_id
action:function(e){
var index=e.detail.value["index"]
var id=this.data.goods[index]._id
}
查
如果需要将查找到的数据添加到data中,请先var that=this之后使用that.setdata({})
const db=wx.cloud.database()
const _=db.commond
//详情见云开发手册command eq,lt,gt,in,and等
//此处查询theAttrYouSearch中等于aaa的记录
db.collection("bank").where({
theAttrYouSearch : _.eq("aaa")
}).get({
//若成功获取,异步操作注意异常
success: res=>{
//打印记录中第一条里goodName属性
console.log(res.data[0].goodName)
}
})
改
const db=wx.cloud.database()
const _=db.commond
//获取goodId的方法同删除操作
db.collection("bank").doc(goodId).update({
//只修改goodNum属性
data: {
goodNum: num
},
success:res=>{
},
fail: res=>{
}
)}