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

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
});
}
})

Related

How to fetch documents from a collection without certain fields from Firestore? [duplicate]

This question already has answers here:
Is there a way to select only certain fields from Firestore?
(1 answer)
How to access a specific field from Cloud FireStore Firebase in Swift
(5 answers)
How to access some fields of firestore in flutter? [duplicate]
(1 answer)
How to get value of some field in firebase firestore android?
(4 answers)
Closed 2 months ago.
I have a collection let's say "files" and a "file" document has 2 main properties (field) : name and content.
(note: I know storing files in a Firestore is not a good idea but that's just an example, let's assume the files are just text files)
When my app opens I want to be able to fetch all user's file names but not the content :
files = [{name: 'a'}, {name: 'b'}, {name: 'c'}, ...]
The reason is obvious I don't want to pull files' content unless the user explicitly ask for from the UI, minimizing the size of data being pulled from Google Cloud and reducing the cost over time.
But collection(db, 'users', user.uid, 'files') seems to return all docs data. Even worst! if one "file" document change, all the docs and their content are being pulled again from the UI onSnapshot listener...
Reading the TypeScript doc I don't see an option to do atomic selection on docs' fields. Am I missing something?

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

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'));

Firebase Firestore order by 2 fields conditionally

I have some documents in Firestore with two Timestamp fields named lastUpdated and lastProcessed in addition to other fields. lastUpdated field is updated when a user updates the record's fields via web console. lastProcessed field is updated when the backend function processes the document (as a result of user clicking a button).
Following are the possible combinations of these 2 fields.
User has only updated the document, but yet to process (lastUpdated == some_timestamp, lastProcessed == '')
User has updated the document, and then processed (lastUpdated < lastProcessed)
User has updated the document, processed and re-updated (lastUpdated > lastProcessed)
My requirement is to execute a query to get a subset of these records (say top 10), ordered by its most recent timestamp. So when evaluating a record for the ordering, lastUpdated field should be considered for scenarios 1 and 3 above. But lastProcessed field should be considered for scenario 2.
Is this possible with Firestore?
When querying the Firestore database it is not possible to execute the logic you explain in your question (i.e. calculate on the fly the scenario to be applied and define which field shall be used in the query).
One classical solution is to add an extra field to the document which contains the value to be queried for. The value of this field can be calculated (according to the business logic) when you modify the document from your frontend, or via a Cloud Function triggered in the backend each time the doc is changed.
The main advantage of using a Cloud Function is to prevent users modifying the value of this field.

FireStore - How to not allow creation of document if there is another document with the same value in a field [duplicate]

This question already has answers here:
Firestore unique index or unique constraint?
(5 answers)
Enforcing unique userIds in Firebase Firestore
(1 answer)
firebase rule for unique property in firestore
(2 answers)
Closed 2 years ago.
I have a Firestore document collection called registrations. Inside registrations, there are documents that contain name, phone number, and age of persons. I want to write the security rules database which allows the creation of person document if and only if another person with the same name does not exist on the database
Thanks in advance
It sounds like you want to keep your names distinct, such as with a UNIQUE constraint in SQL.
It is not possible to query specific document fields in Firestore security rules.
There are two ways to do what you want with Firestore:
use name as your document id
or create a collection /usedNames with name as document id, so that in your security rule you can test:
let name = request.resource.data.name;
return exists(/usedNames/$(name)) == false

firebase firestore check if document with property and value exists [duplicate]

This question already has answers here:
Cloud Firestore: Enforcing Unique User Names
(8 answers)
Closed 3 years ago.
I am currently trying to verify before a user creates data in the database if the data exists. Even unter an other Document id.
Like this: User creates data, firestore rules gets all documents in collection and checks if the property name is the same as from the user provided. If yes, return unauthorized access.
At this point I have:
function checkIfCatExists(){
return get(/databases/$(database)/documents/category/$(documents)).data.name != null;
}
But this does not work. Do you guys have an idea? I could create a function for that but I want to do as much as possible with rules.
There is no way to search a collection for a specific value in security rules, as that operation wouldn't scale.
If you want to ensure unique user names, you'll have to create a collection where you use the user names as the key. You can then use the exists function in your security rules, to check if the name already exists in the collection.
Also see:
Cloud Firestore: Enforcing Unique User Names
Firestore security rule to check if character username already exists
Firestore security rules - can I query for a document with specific fields?
I want to write a rule that will don't allow add same document second time

Resources