微信云开发数据库增删改查

数据库的增删改查


注意 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=>{
          
      }
)}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值