一开始想的是直接
db.collection('media').get()
不就完了吗?谁想到文档中有这个限制
获取一个集合的数据
如果要获取一个集合的数据,比如获取 todos 集合上的所有记录,可以在集合上调用
get
方法获取,但通常不建议这么使用,在小程序中我们需要尽量避免一次性获取过量的数据,只应获取必要的数据。为了防止误操作以及保护小程序体验,小程序端在获取集合数据时服务器一次默认并且最多返回 20 条记录,云函数端这个数字则是 100。开发者可以通过limit
方法指定需要获取的记录数量,但小程序端不能超过 20 条,云函数端不能超过 100 条。
wqnmd,
官方文档只有云函数的做法:
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,
}
})
}
我修改了一下试着应用到小程序上:
db.collection('media').count().then(res =>{
let total = res.total;
// 计算需分几次取
const batchTimes = Math.ceil(total / MAX_LIMIT)
// 承载所有读操作的 promise 的数组
const tasks = []
for (let i = 0; i < batchTimes; i++) {
const promise = db.collection('media').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
promise.then(res =>{
// console.log(res.data)
tasks.push(res.data)
// console.log(tasks)
})
}
console.log(tasks)
})
发现这东西tm是异步的,沃兔了。
最后版本
db.collection('media').count().then(async res =>{
let total = res.total;
// 计算需分几次取
const batchTimes = Math.ceil(total / MAX_LIMIT)
// 承载所有读操作的 promise 的数组
for (let i = 0; i < batchTimes; i++) {
await db.collection('media').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get().then(async res => {
let new_data = res.data
let old_data = that.data.allRecords
that.setData({
allRecords : old_data.concat(new_data)
})
})
}
console.log(that.data.allRecords[0])
})