[英]How to save a single document field in cloud firestore into a local variable in flutter?
[英]How to update a single field of all documents in firestore using flutter?
我在數據庫中有 100 個用戶文檔,我必須在所有文檔中將一個字段更新為 0。 我們該怎么做呢?
Firestore 不提供類似 SQL 的“update where”命令來一次更新所有內容,因此您必須:
嘗試執行以下操作
DocumentSnapshot
並使用 reference 屬性獲取其DocumentReference
object 並且對於每個文檔,使用其新值更新字段 void updateNotificationCount() async {
FirebaseUser _currentUser = await FirebaseAuth.instance.currentUser();
String authid = _currentUser.uid;
var snapshots =
activityFeedRef.document(authid).collection('feedItems').snapshots();
try {
await snapshots.forEach((snapshot) async {
List<DocumentSnapshot> documents = snapshot.documents;
for (var document in documents) {
await document.reference.updateData(<String, dynamic>{
'seen': true,
});
}
});
} catch (e) {
print(e.toString());
}
}
上面的代碼只是在用戶單擊通知托盤時立即將所有未讀通知從 false 更新為 true
正如@Doug提到的那樣,沒有直接的方法,您必須查詢數據,從QueryDocumentSnapshot
獲取DocumentReference
並對其調用update
。
var collection = FirebaseFirestore.instance.collection('collection');
var querySnapshots = await collection.get();
for (var doc in querySnapshots.docs) {
await doc.reference.update({
'single_field': 'newValue',
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.