假设我们已有一个集合 todos,其中包含以下格式记录:

    我们先来看看如何获取一个记录的数据,假设我们已有一个 ID 为 todo-identifiant-aleatoire 的在集合 todos 上的记录,那么我们可以通过在该记录的引用调用 get 方法获取这个待办事项的数据:

    1. db.collection('todos').doc('todo-identifiant-aleatoire').get({
    2. success: function(res) {
    3. // res.data 包含该记录的数据
    4. console.log(res.data)
    5. }
    6. })
    1. db.collection('todos').doc('todo-identifiant-aleatoire').get().then(res => {
    2. // res.data 包含该记录的数据
    3. console.log(res.data)
    4. })

    我们也可以一次性获取多条记录。通过调用集合上的 where 方法可以指定查询条件,再调用 get 方法即可只返回满足指定查询条件的记录,比如获取用户的所有未完成的待办事项:

    where 方法接收一个对象参数,该对象中每个字段和它的值构成一个需满足的匹配条件,各个字段间的关系是 "与" 的关系,即需同时满足这些匹配条件,在这个例子中,就是查询出 todos 集合中 _openid 等于 user-open-iddone 等于 false 的记录。在查询条件中我们也可以指定匹配一个嵌套字段的值,比如找出自己的标为黄色的待办事项:

    1. db.collection('todos').where({
    2. _openid: 'user-open-id',
    3. color: 'yellow'
    4. }
    5. })
    6. success: function(res) {
    7. console.log(res.data)
    8. }
    9. })
    1. db.collection('todos').where({
    2. _openid: 'user-open-id',
    3. 'style.color': 'yellow'
    4. })
    5. .get({
    6. success: function(res) {
    7. console.log(res.data)
    8. }
    9. })

    如果要获取一个集合的数据,比如获取 todos 集合上的所有记录,可以在集合上调用 get 方法获取,但通常不建议这么使用,在小程序中我们需要尽量避免一次性获取过量的数据,只应获取必要的数据。为了防止误操作以及保护小程序体验,小程序端在获取集合数据时服务器一次默认并且最多返回 20 条记录,云函数端这个数字则是 100。开发者可以通过 limit 方法指定需要获取的记录数量,但小程序端不能超过 20 条,云函数端不能超过 100 条。

    也可以用 Promise 风格调用:

    1. db.collection('todos').get().then(res => {
    2. // res.data 是一个包含集合中有权限访问的所有记录的数据,不超过 20 条
    3. console.log(res.data)
    1. const cloud = require('wx-server-sdk')
    2. cloud.init()
    3. const MAX_LIMIT = 100
    4. exports.main = async (event, context) => {
    5. // 先取出集合记录总数
    6. const countResult = await db.collection('todos').count()
    7. const total = countResult.total
    8. // 计算需分几次取
    9. const batchTimes = Math.ceil(total / 100)
    10. // 承载所有读操作的 promise 的数组
    11. const tasks = []
    12. for (let i = 0; i < batchTimes; i++) {
    13. const promise = db.collection('todos').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    14. tasks.push(promise)
    15. }
    16. // 等待所有
    17. return (await Promise.all(tasks)).reduce((acc, cur) => {
    18. return {
    19. data: acc.data.concat(cur.data),
    20. errMsg: acc.errMsg,
    21. }
    22. }