Flutter: Better way to update many documents in a single call [duplicate] - firebase

This question already has answers here:
Can Firestore update multiple documents matching a condition, using one query?
(8 answers)
Firestore update all documents in collections
(6 answers)
How to do a bulk update in Firestore
(4 answers)
Closed 9 months ago.
I have a function that allows a user to change their username, simply using firebase update({}). Every time a user sends a message in my chat page, it saves it as a documents on firebase with related data, user name, time message was sent etc.
The function below is for a chat page, which works how I want it to. it takes whatever the current users username and updates all past messages with the users new current username. I want to know if their is a better way to achieve this.
How can I change a single value in any amount of documents, which obviously have different ids, in one single call?
List<String> testList = []; //<--- List of document IDs of previous messages user has sent
FirebaseFirestore.instance
.collection('users')
.doc(loggedInUser.uid)
.update({'messageID': testList});
for (var item in testList) {
var collection = FirebaseFirestore.instance
.collection("chatrooms")
.doc(chatroom)
.collection("users")
.doc('ggg')
.collection("userMessage");
collection
.doc(item) // <-- Doc ID where data should be updated.
.update({'username': loggedInUser.userName.toString()}) // <-- Updated data
.then((_) => print('Updated'))
.catchError((error) => print('Update failed: $error'));

Related

How to update a particular field in all the documents of a collection in cloud firestore? [duplicate]

This question already has answers here:
How to update a single field of all documents in firestore using flutter?
(3 answers)
Can Firestore update multiple documents matching a condition, using one query?
(8 answers)
Closed 12 months ago.
I am developing a Quiz App using flutter, firebase and cloud firestore in which users can play a quiz only once per day and the total score of all users will be reset to zero after every month. I am trying to achieve this by creating these two fields in each user document in the users collection:
isReadyToPlay: This field stores a boolean value 'true' if user didn't play the quiz, and changes to 'false' when user completes the quiz. I display a "start quiz" button if the value is true and remove it if the value is false. But I need to update this value to 'true' again, to allow the user to play the quiz the next day. So how do I update this field in all the documents from the collection?
total_score: This field stores the total score of all the quizzes a user plays. I want to reset this score to zero after every month. So again, I need to update this field in all the documents of the users collection.
I want to update the mentioned fields in all the documents at once from the admin end. If this is not possible, what could be a work around to achieve this?
You can do it like this first get all the documents as a snapshot and just update the required field of each document in the snapshot.
FirebaseFirestore.instance.collection('users').get().then((snapshot) {
for (DocumentSnapshot ds in snapshot.docs) {
ds.reference.update({
'isReadyToPlay': true, //True or false
'totalScore': 254 //Your new value
});
}
})

how to get collection list from document Id in flutter Firestore? [duplicate]

This question already has answers here:
Flutter & Firebase: Return list of collections
(2 answers)
Fetching all collections in Firestore
(3 answers)
How to list subcollection on firestore? [duplicate]
(1 answer)
Closed 1 year ago.
i want "a9XvvHPEvhfDWTXe8HqPqWuP2gg1" this documentId collection list.
FirebaseFirestore.instance
.collection('tbl_FriendList').doc(
'a9XvvHPEvhfDWTXe8HqPqWuP2gg1').get().then((event) {});
You can't do that with the Flutter sdk. You'll need to restructure your data.
Retrieving a list of collections is not possible with the mobile/web
client libraries. You should only look up collection names as part of
administrative tasks in trusted server environments. If you find that
you need this capability in the mobile/web client libraries, consider
restructuring your data so that subcollection names are predictable.
https://firebase.google.com/docs/firestore/query-data/get-data#list_subcollections_of_a_document
As per you image, seems like there is no document in this ID. You only have sub-collections.
To get sub-collection you have to improve your query and you should know your sub-collection name as mentioned below
await FirebaseFirestore.instance
.collection('tbl_FriendList')
.doc('a9XvvHPEvhfDWTXe8HqPqWuP2gg1')
.collection('collectionPath')
.get();
Or you have to store data in db like this
a9XvvHPEvhfDWTXe8HqPqWuP2gg1 > collectionName > documents
FirebaseFirestore.instance
.collection('tbl_FriendList')
.doc('a9XvvHPEvhfDWTXe8HqPqWuP2gg1')
.collection('collectionName')
.add({'data': 'data123'});
after that you can get data as mentioned below
FirebaseFirestore.instance
.collection('tbl_FriendList')
.doc('a9XvvHPEvhfDWTXe8HqPqWuP2gg1')
.collection('collectionName')
.get()
.then((value) => {});
This query will return all data you have in collectionName sub-collection.

Is my Sub Collection is Also fetched when Fetching the Collection? [duplicate]

This question already has an answer here:
When fetching document from Firestore, am I also getting the collections inside this document?
(1 answer)
Closed 1 year ago.
I have a subcollection "Ratings" inside this "Posts" collection so when i get any post will this collection will be fetched automatically or i have to reference it separately. And if this subcollection Ratings is fetched with the post so it'll be count as a separate read or same as the Post read?
final CollectionReference postsCollection =
FirebaseFirestore.instance.collection("posts");
response = await FirebaseFirestore.instance
.collection("posts")
.get();
Getting a collection will NOT get the subcollections. The subcollections need a separate read.... and reading collection or subcollection considered read.

How can I use multiple order by in real time database flutter to order data by specific field? [duplicate]

This question already has answers here:
Query based on multiple where clauses in Firebase
(8 answers)
Closed 2 years ago.
I am trying to short "realtime database" result according to "date" in flutter. But I cant use multiple orderByChild('child_name'). It throw an error. My code is
final String path = 'jsondata';
final _dbRef = FirebaseDatabase.instance.reference();
_dbRef.child(path)
.orderByChild('trade_code').equalTo('GP')
.once()
.then((DataSnapshot snapshot) {
snapshot.value.forEach((key, value) {
print(value);
});
});
The result is
Result
Now I want to sort the data by Date.
How can I do that?
It's not possible to use multiple oder at the same time in Firebase Realtime Database. Please check the following doc:
Firebase Realtime Database Query
To achieve that type of complex query I prefer that you should migrate from the Realtime Database to Firebase Cloud Firestore. Check the following resource:
Simple and Complex Dynamic Query in Could Firestore
Your Firestore instance would be:
FirebaseFirestore.instance
.collection('products')
.where('trade_code', isEqualTo: 'GP')
.orderBy('date')

Fetch documents from multiple subcollections - Firebase [duplicate]

This question already has answers here:
Firestore query subcollections
(11 answers)
Closed 3 years ago.
I'm creating a web app for admin with firebase integration, this web app is used by admin to monitor posts or comments posted by user from Android or iOS app developed in ionic.
I'm using Firebase firestore, and following is the database design
posts/{postsDocument}/comments/{commentsDocument}.
The comments here is sub-collection for postsDocument that holds all the comments for a particular post. Also postDocument and commentsDocument contains Firebase uid of the user.
My problem is, whether it's possible to fetch all the comments commented by a particular user. I can query a single collection, but in this scenario commentsDocument is a subcollection and i want to fetch all comments across all the post by a user for monitoring purpose.
You can check firebase collection group query
var commentsQuery = db.collectionGroup('comments').where('commentOwnerID', '==', userId);//userId - firebase id of the user who commented
commentsQuery.get().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.id, ' => ', doc.data());
});
});
Also you might have to create index that supports your query, check console for the the link for creating index

Resources