firestoreSet
The firestoreSet
function is a higher-order function that takes a collection path and an options object, and returns a function that can be used to set a documents at a specific address.
Usage
You can use the firestoreSet
function to set a document at a specified path. The first argument is the slash-separated path of the collection containing the document.
Subcollections
Collections don’t have to be at the top level of the Firestore, adding slashes will set the document in a subcollection. For example, if you want to set 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 postId from the comment itself, assuming the comment 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 object of the provided 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 firestoreSet
is an optional object allowing for additional configuration. This object can have a property addMetadata
which, if true, adds metadata to the document.