问题
I have a 100 user documents in database, and I have to update one field to 0 in all documents. How do we do it?
回答1:
Firestore doesn't offer a SQL-like "update where" command that updates everything at once, so you will have to:
- Query for the documents to update
- Iterate each DocumentSnapshot and get its DocumentReference object using the reference property
- For each document, update the field with its new value
回答2:
Try doing the following
- Query the documents to update
- Go through each
DocumentSnapshot
and get itsDocumentReference
object using the reference property and for each document, update the field with its new value
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());
}
}
The code above simply updates all unread notification from false to true immediately the user clicks on the notification tray
来源:https://stackoverflow.com/questions/63321875/how-to-update-a-single-field-of-all-documents-in-firestore-using-flutter