簡體   English   中英

如何使用 flutter 更新 Firestore 中所有文檔的單個字段?

[英]How to update a single field of all documents in firestore using flutter?

我在數據庫中有 100 個用戶文檔,我必須在所有文檔中將一個字段更新為 0。 我們該怎么做呢?

Firestore 不提供類似 SQL 的“update where”命令來一次更新所有內容,因此您必須:

  1. 查詢要更新的文檔
  2. 迭代每個DocumentSnapshot並使用reference 屬性獲取其 DocumentReference object
  3. 對於每個文檔,使用其新值更新字段

嘗試執行以下操作

  1. 查詢要更新的文檔
  2. Go 通過每個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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM