下面的代码失败,错误为9 FAILED_PRECONDITION: The requested snapshot version is too old.
const ref = db.collection('Collection');
const snapshot = await ref.get();
snapshot.forEach((doc,index) => {
...use data
})
Getting all documents from one collection in Firestore
编辑:
getData();
async function getData(doc) {
let snapshot = await global.db.collection('Collection').orderBy().startAfter(doc).limit(5000).get();
const last = snapshot.docs[snapshot.docs.length - 1];
snapshot.forEach((doc,index) => {
//...use data
})
if (snapshot.docs.length < 5000) {
return;
}
else {
getData(last)
}
}
编辑2(工作,有点慢,按顺序读取,一次5000个文档):
let snapshot = null;
let totalIndex = 0;
await getData();
async function getData(doc) {
if (!doc) {
const first = await global.db.collection("collection").doc("docID");
snapshot = await global.db.collection('collection').orderBy(admin.firestore.FieldPath.documentId()).startAt(first).limit(5000).get();
}
else {
snapshot = await global.db.collection('Prompts').orderBy(admin.firestore.FieldPath.documentId()).startAfter(doc).limit(5000).get();
}
const last = snapshot.docs[snapshot.docs.length - 1];
snapshot.forEach((doc,index) => {
console.log(totalIndex++);
//...use data
})
if (snapshot.docs.length < 5000) {
return;
}
else {
getData(last)
}
}
1条答案
按热度按时间xe55xuns1#
因为你一开始调用
getData()
时没有任何参数,所以doc
在函数体中是undefined
,调用startAfter(undefined)
是无效的。您可以选择添加
startAfter
,如下所示: