[英]How to get all collections and documents without their names in Cloud Firestore (web)
[英]Firestore update all documents in collections
我有一個名為 users 的 firestore 集合,每個用戶都有一個帶有字段 score 的生成 id:
users
0e8X3VFL56rHBxxgkYOW
score : 4
3SeDjrgAWMmh3ranh2u
score : 5
您可以獲取集合中的所有文檔,獲取它們的 id 並使用這些 id 執行更新:
db.collection("cities").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
doc.ref.update({
capital: true
});
});
});
由於某種奇怪的原因,接受的答案( thehamzarocks )對我不起作用,沒有任何文件被更新。 也許 AngularFire2 中存在錯誤。 無論如何,我決定遍歷 QuerySnapshot 的 docs 數組而不是使用它的 forEach 方法,並將每個更新添加到批處理隊列中。 批處理批量操作也比為每個更新操作發送一個新的更新請求更有效。
resetScore(): Promise<void> {
return this.usersCollectionRef.ref.get().then(resp => {
console.log(resp.docs)
let batch = this.afs.firestore.batch();
resp.docs.forEach(userDocRef => {
batch.update(userDocRef.ref, {'score': 0, 'leadsWithSalesWin': 0, 'leadsReported': 0});
})
batch.commit().catch(err => console.error(err));
}).catch(error => console.error(error))
}
批量更新很好,但請記住,每個事務最多只能更新 500 個文檔。 如果不經常進行此重置,最簡單的方法可能是:
async function resetScores() {
const collection = await db
.collection("users")
.get()
collection.forEach(doc=> {
doc.ref
.update({
score: 0
})
})
}
Firestore 無法在不知道文檔 ID 的情況下批量更新文檔。 您必須以某種方式知道要更新的每個文檔的文檔 ID(執行查詢或批量查詢),並單獨更新每個文檔。
我在尋找類似解決方案時遇到了這篇文章。 Firestore 現在具有批量寫入功能,可以一次性更新所有文檔。 對於較少的文檔,這可能是一個理想的解決方案。
更新@thehamzarocks 的回答:
const batch = db.batch()
db.collection('cities').get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
const docRef = db.collection('cities').doc(doc.id)
batch.update(docRef, { capital: true })
});
batch.commit();
});
對不起,如果問題很舊,但我認為為這個問題提供新答案可能對其他人也有用。 我設法使用以下命令批量更新列表的條目:
this.db
.list<User[]>('users')
.set('/', users);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.