firestoreUpdate
The firestoreUpdate
function is a higher-order function that returns a function that updates a document in a collection.
Usage
You can use the firestoreUpdate
function to update a document from a collection. The first argument is the slash-separated path of the collection.
Subcollections
Collections don’t have to be at the top level of the Firestore, adding slashes will update the document in a subcollection. For example, if you want to update a post in a collection of posts for a specific user:
Dynamic Paths
Using subcollections is a common pattern in Firestore since it makes writing security rules much easier. To make our function more reusable, we can use a function that takes an arguments object and returns a string representing the path:
Even more convenient is to pull the userId from the post itself, assuming the post contains it. This can be done by using the data
property of the arguments object which contains the data that will be written to the document:
Return Value
The function returns a Promise that resolves with a DocumentReference
to the newly created document.
Type Safety
If a type parameter is provided, the returned function will be typesafe. It will allow any Partial
of the provided type to be passed as the second argument. It will not allow any other type to be passed as the second argument.
The provided type definitions will help you to avoid common mistakes, but they are not realtime validation. You can still write invalid data to Firestore if you don’t use the provided functions correctly.
Options
The second argument to firestoreUpdate
is an optional object allowing for additional configuration. This object can have a property addMetadata
which, if true, adds metadata to the document.