# Collection.get(): Promise<Object>

获取集合数据,或获取根据查询条件筛选后的集合数据。

# 返回值

# Promise.<Object>

属性 类型 说明
data Array.<Object> 查询的结果数组,数据的每个元素是一个 Object,代表一条记录

# 使用说明

统计集合记录数或统计查询语句对应的结果记录数

小程序端与云函数端的表现会有如下差异:

  • 小程序端:如果没有指定 limit,则默认且最多取 20 条记录。
  • 云函数端:如果没有指定 limit,则默认且最多取 100 条记录。 如果没有指定 skip,则默认从第 0 条记录开始取,skip 常用于分页,例子可见第二个示例代码。

# 示例代码 1

获取我的待办事项清单:

const cloud = require('qq-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
exports.main = async (event, context) => {
  return await db.collection('todos').where({
    _openid: 'xxx' // 填入当前用户 openid
  }).get()
}
1
2
3
4
5
6
7
8
9
10

# 示例代码 2:分页取数据

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

db.collection('todos')
  .where({
    _openid: 'xxx', // 填入当前用户 openid
  })
  .skip(10) // 跳过结果集中的前 10 条,从第 11 条开始返回
  .limit(10) // 限制返回数量为 10 条
  .get()
  .then(res => {
    console.log(res.data)
  })
  .catch(err => {
    console.error(err)
  })
1
2
3
4
5
6
7
8
9
10
11
12
13

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

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

const cloud = require('qq-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
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,
    }
  })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26