[英]How to update a single field of all documents in firestore using flutter?
I have a 100 user documents in database, and I have to update one field to 0 in all documents.我在数据库中有 100 个用户文档,我必须在所有文档中将一个字段更新为 0。 How do we do it?
我们该怎么做呢?
Firestore doesn't offer a SQL-like "update where" command that updates everything at once, so you will have to: Firestore 不提供类似 SQL 的“update where”命令来一次更新所有内容,因此您必须:
Try doing the following尝试执行以下操作
DocumentSnapshot
and get its DocumentReference
object using the reference property and for each document, update the field with its new value 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());
}
}
The code above simply updates all unread notification from false to true immediately the user clicks on the notification tray上面的代码只是在用户单击通知托盘时立即将所有未读通知从 false 更新为 true
As @Doug mentioned there's no direct way, you'll have to query the data, get the DocumentReference
from QueryDocumentSnapshot
and invoke update
on it.正如@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.