微信小程序云开发服务端数据库API 获取集合数据


当前第2页 返回上一页

获取我的第二页的待办事项清单,假设一页 10 条,现在要取第 2 页,则可以指定 skip 10 条记录

const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
  return await db.collection('todos')
    .where({
      _openid: 'xxx', // 填入当前用户 openid
    })
    .skip(10) // 跳过结果集中的前 10 条,从第 11 条开始返回
    .limit(10) // 限制返回数量为 10 条
    .get()
}

示例代码 3:取集合所有数据

获取集合中的所有待办事项清单:因为有默认 limit 100 条的限制,因此很可能一个请求无法取出所有数据,需要分批次取:

const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const MAX_LIMIT = 100
exports.main = async (event, context) => {
  // 先取出集合记录总数
  const countResult = await db.collection('todos').count()
  const total = countResult.total
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('todos').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}

标签:微信小程序

返回前面的内容

相关阅读 >>

微信小程序云开发 预付费

微信小程序 启动性能

微信小程序 小程序测速

微信小程序 城市服务实名信息校验

sdk数据库 aggregate限制记录数

微信小程序 运力方使用onagentposquery

微信小程序api 录音-获取录音管理器

微信小程序 applyplugin

微信小程序 性能trace工具

微信小程序 多线程worker

更多相关阅读请进入《微信小程序》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...