日常积累小程序

【七】10分钟精通微信小程序 | 增删改查

2019-03-22  本文已影响63人  红色火苗

查询数据

获取一个记录的数据

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

db.collection('todos').doc('todo-identifiant-aleatoire').get({
  success(res) {
    // res.data 包含该记录的数据
    console.log(res.data)
  }
})

Promise 风格调用:

db.collection('todos').doc('todo-identifiant-aleatoire').get().then(res => {
  // res.data 包含该记录的数据
  console.log(res.data)
})

获取多个记录的数据

db.collection('todos').where({
  _openid: 'user-open-id',
  done: false
})
  .get({
    success(res) {
    // res.data 是包含以上定义的两条记录的数组
      console.log(res.data)
    }
  })

where 方法接收 一个对象,对象里的元素关系为 且 即 必须同时满足对象里的元素条件

也可以用 "点表示法" 表示嵌套字段:

db.collection('todos').where({
  _openid: 'user-open-id',
  'style.color': 'yellow'
})
  .get({
    success(res) {
      console.log(res.data)
    }
  })

获取整个集合的数据,限制20条记录

db.collection('todos').get({
  success(res) {
    // res.data 是一个包含集合中有权限访问的所有记录的数据,不超过 20 条
    console.log(res.data)
  }
})

promise风格

db.collection('todos').get().then(res => {
  // res.data 是一个包含集合中有权限访问的所有记录的数据,不超过 20 条
  console.log(res.data)
})

云函数获取 限制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) => ({
    data: acc.data.concat(cur.data),
    errMsg: acc.errMsg,
  }))
}

推荐微信小程序阅读:

【十一】 10分钟精通微信小程序 | 云函数管理端
【十】 10分钟精通小程序 | 云函数异步返回结果
【九】10分钟精通微信小程序 | 云函数
【八】 10分钟精通微信小程序云存储 | 云存储
【七】10分钟精通微信小程序 | 增删改查
【六】10分钟精通微信小程序 | 增删改查
【五】10分钟精通微信小程序 | 云数据库增删改查
【四】10分钟精通微信小程序 | 云控制台
【三】10分钟精通微信小程序 | 光速入门
【二】10分钟精通微信小程序云开发 | 多图上传并存储路径到云数据库
【一】10分钟精通微信小程序 | 获取用户openid

上一篇 下一篇

猜你喜欢

热点阅读