I want to update the field code
in all the documents of a collection. Since it takes multiple write operations, I want to update the collection altogether.
This is the code (used batched writes as given in the documentation) :
const batch = writeBatch(db);
const userRef = doc(db, "users", userId)
const repoRef = doc(userRef, "repos", repo)
const filesRef= collection(repoRef, "files")
batch.update(filesRef, data);
The data object:
{
README: {languageId: 45, code: 'slkjf', name: 'README'}
main: {languageId: 62, name: 'main', code: 'haah'}
}
Error:
No error shown
What is the solution and is this the best method, or should I use a map method and recursively update the field in every document?
2
Answers
If you want to update all documents inside a collection so first you’ll need to get all documents of this collection:
Then you’ll need to loop through all these documents and add the change to batch:
You can find more about this here.
Hope this helps
The first parameter of a call to
WriteBatch#update()
is aDocumentReference
. In your code you instead try to pass in aCollectionReference
.To write the code property of each entry in a given object to your database, you first must iterate through the object and add update operations into your batch before committing it to the server.
For the given object and references:
You can add update operations into the batch like so:
Once you are ready to apply the changes to the server, call the commit method and handle the returned Promise object.
Batched writes have a limit of 500 operations per batch, so to handle that you can use this function to automatically create more batches as needed.
Note: Atomic updates are not guaranteed across multiple batches, only for each individual batch.