2022/4/7 云开发

本文详细介绍了微信小程序中如何使用数据库,包括初始化、查询、插入、更新和删除数据,以及如何进行条件筛选和数据监听。此外,还讨论了云函数的添加、调用和使用Promise处理回调,以及数据库的计数和监听功能。同时,文章提到了数据的分页和排序策略,以及如何在云函数中实现更复杂的查询操作。
摘要由CSDN通过智能技术生成

1-7

数据库

官方文档

使用

collection

  1. 初始化
const db=wx.cloud.database()
  1. 连接数据库
db.collection('demouser')
//demouser为表名

获取所有记录的示例:

db.collection('demouser').get({
      success:res=>{
        console.log(res)
      }
    })

查询get

获取所有元素后可通过wx:for循环渲染

 db.collection('demouser').get({
      success:res=>{
        //console.log(res)
        this.setData({
          user:res.data
        })
        console.log(this.data.user)
      }
    })
    //获取所有元素,并将其中的data给user数组

通过id查询:通过**.doc**方法,.doc只能方id

db.collection('demouser').doc('d4107ab1624ec8310593163d1d6415ba').get({
      success:res=>{
        this.setData({
          user:res.data
        })
        console.log(this.data.user)
      }
    })

promies化的方法进行处理回调函数可以防止回调地狱(.then或.catch的链式方法)

 db.collection('demouser').get().then(res=>{
      this.setData({
          user:res.data
        })
        console.log(this.data.user)
    })

where进行条件筛选

db.collection('demouser').where({
    identity:1
  }).get().then(res=>{
        this.setData({
            user:res.data
          })
          console.log(this.data.user)
      })

插入add

db.collection('demouser').add({
      data:{
        name:this.data.name,
        age:this.data.age,
        identity:this.data.identity
      }
    }).then(res=>{
      console.log(res)
    })

在插入数据时,可以添加节流操作
简单的节流操作可在可在showLoading中加入mask属性。

wx.showLoading({
      title: '数据添加中。。。',
      mask:true
    })

更新updata和set,删除remove

对于更新操作和删除操作,小程序端仅可以通过.doc的id属性进行更新或删除,.where需要在云函数进行实现。
在小程序端,对于updata,set,remove,仅在所以有用户可读,仅创建者可读写仅创建者可读写两种权限下使用。

计数count

count的效率高于get,因为其只获得数量

数据库监听watch

watch文档
目前实验结果:在小程序端,无论watch定义在什么地方,只要数据发生变化都会被调用。
例如:有监听函数datawatcher

dataWatcher(){
  db.collection('demouser').watch({
    onChange:res=>{
      console.log(res)
      console.log(res.docChanges)
      console.log('数据监听触发')
      this.setData({
        allitem:res.docs
      })
      this.count_test()
    },
    onError:err=>{
      console.log(err)
    }
  })
},

不论其在什么地方被调用,如onLoad,onPullDownRefresh或自己定义的监听函数中,只要数据库中的数据发生了变化,就会被调用。但是若只定义datawatcher,却不对其进行调用,则不会起效。

构建查询条件

官方文档

  • where:条件查询
  • orderBy:排序
  • limit+skip:可以实现分页操作
  • field:传入一个对象,给出需要查出的属性,可提高查询效率

command

官方文档

初始化

const _=db.command

and,or对于多条属性同时操作

在这里插入图片描述
多属性同时操作时,使用数组[],其中元素为对象{},对象中包含属性。以实现对多属性查询

云函数

添加云函数

新建云函数

右键cloudfunctions,选择新建Node.js新建一个云函数,云函数编写完或更改后,需要上传并部署。
云函数中需要初始化

const db=cloud.database()

调用云函数

 wx.cloud.callFunction({
      name:'getData'
    }).then(res=>{
      console.log(res)
    })

promies

await:等待异步请求完成

云存储

三级标题

四级标题
五级标题
六级标题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值