微信小程序云开发:数据库增删改查及查询条件

本文详细介绍了如何在微信小程序中进行数据库操作,包括连接数据库、查询数据、添加、更新和删除记录,以及各种高级查询技巧如指定返回字段、排序、分页等,帮助开发者高效管理小程序中的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

查询数据库中的数据

定义一个const常量,使用wx.cloud.database()方法

const db = wx.cloud.database();   
//将db连接数据库,用const定义,定义为全局变量

使用collection().doc().get()方法获取数据库中的数据

db.collection("Demolist").get({   //获取数据库,db为已连接到数据库的值
      success:res=>{
        this.setData({
          dataList:res.data
        })
        console.log(res);
      }
      
db.collection("Demolist").doc("id").get({
      //doc中写入id值可以查询特定的数据,不加doc全部获取
      success:docRes=>{
        this.setData({
          docList:docRes.data
        })
      }
    })

//打印结果
//{data: Array(2), errMsg: "collection.get:ok"}
//{data: {…}, errMsg: "document.get:ok"}

通过自定义的字段去查询数据:Collection.where(Object obj)

查询与obj中字段的变量值相同的记录

db.collection("Demolist").where({ author:"小明" }).get({
      //使用where({})进行自定义字段查询数据,只有一条记录但回调结果仍是数组
      success:wheRes=>{
        console.log(wheRes);      
      }
    })
   
//打印结果
//{data: Array(1), errMsg: "collection.get:ok"}

链式回调:then( function fun )

相当于success:res=>{ }
链式回调使代码更简洁

//回调地狱,链式回调,相当于在success中又一次进行db.collection().get({ success:res=>{} })
//使用then方法与get中写入success回调函数作用相同
   
    db.collection("Demolist").get().then(theRes=>{
      console.log(theRes);
    }).then(theRes1=>{
      console.log(theRes1);
    })


    db.collection("Demolist").get({
      success:theRes=>{
        console.log(theRes);
        db.collection("Demolist").get({
          success:theRes1=>{
            console.log(theRes1);
          }
        })

      }
    })

    //上面两段代码运行结果相同

添加数据到数据库:Collection.add(Object obj)

向数据库中添加一条记录,obj中的data中写入添加的字段

<button type="primary" bindtap="addData">添加一条数据</button>
addData(){                        //自定义的事件函数
    db.collection("Demolist").add({
          data:{    //需要添加的数据,Object类型
             title:"测试标题",
            author:"一个作者",
            content:"KFHAKHFNSUFHA"
          }
      }).then(res=>{  //then回调函数
          console.log(res);
      })
},

数据更新:Collection.update()

只有通过add()添加的数据才能用update()进行更新,若是在云端数据库手动添加的记录需要使用云函数更新,使用update()返回成功但不会修改 stats:{update:0}

addData(){
    db.collection("Demolist").add({
      data:{
        title:"111",
        author:["222","333"],
        content:"ccc"
      }
    }).then(res=>{ console.log(res) })
},


updateData(){
    db.collection("Demolist").doc("id").update({
    //该条记录为云数据库手动添加的记录
      data:{
        author:"更改的作者"
      }
    }).then(res=>{ 
      console.log(res)
    })
    //update()修改返回成功但无效,返回显示stats:{update: 0}
    
},

更新指令:remove(),push(),pop()…

command的方法

查看记录条数:count()

getDataNum(){  //获取记录个数 total
    db.collection("Demolist").count().then(res=>{
      console.log(res);
    })
  },
  
  //打印结果
  // {total: 2, errMsg: "collection.count:ok"}

限制数量:Collection.limit(number num)

指定查询结果集数量上限
在小程序端默认及最大上限为 20,在云函数端默认及最大上限为 1000

LimitBtn(){
    db.collection("Demolist").limit(2).get().then(res=>{
      console.log(res);
    })
 },
 
 // 打印结果
 // {data: Array(2), errMsg: "collection.get:ok"}

排序:Collection.orderBy(String str, String ord)

参数str表示根据该字段进行排序,ord表示排序类型(asc为升序,desc为降序)

orderByBtn(){
    //以hits字段进行顺序排序,desc为降序
    db.collection("Demolist").orderBy("hits","asc").get().then(orderRes=>{
      console.log(orderRes);
    })

    //多级orderBy()
    //先以hits字段倒序排序,若hits字段相同,再按id字段顺序排序
    db.collection("Demolist").orderBy("hits","desc").orderBy("id","asc").get().then(orderRes=>{
      console.log(orderRes);
    })
},

跳过数据:Collection.skip(number num)

指定查询返回结果时从指定序列后的结果开始返回
配合limit()可实现分页功能

skipBtn(){
    //Demolist中有4条记录
    //skip(num) 跳过num条记录,从第num+1条记录开始读取,配合limit()可以实现分页功能,
    db.collection("Demolist").limit(2).skip(2).get().then(skipRes=>{
      console.log(skipRes);
    })

    db.collection("Demolist").limit(2).skip(3).get().then(skipRes=>{
      console.log(skipRes);
    })
},

// 打印结果
// {data: Array(2), errMsg: "collection.get:ok"}
// {data: Array(1), errMsg: "collection.get:ok"}

指定返回字段:Collection.field(Object obj)

方法接受一个必填对象用于指定需返回的字段,对象的各个 key 表示要返回或不要返回的字段,value 传入 true|false(或 1|-1)表示要返回还是不要返回。

fieldBtn(){
    db.collection("Demolist").field({
      title:true,
      author:true
    }).get().then(fieRes=>{
      console.log(fieRes);
    })
  },

//打印结果
//data: Array(4)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚风也很浪漫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值