There are two methods that we can use to add document data to the Firebase Version 9 Cloud Firestore.
Example of addDoc()
Here is an example of using the addDoc() method to add a new document to a Firestore collection in Firebase version 9 Cloud Firestore
In this example, we first import the necessary Firebase modules and initialize the Firebase app with your Firebase config. Then, we get a Firestore instance using getFirestore().
Next, we define the collection where we want to add the new document using collection(). We also define the document data as an object with name, email, and age fields.
Finally, we use the addDoc() method to add the document to the collection. This method returns a DocumentReference object, which contains the ID of the newly added document. We log this ID to the console for demonstration purposes.
Note that the addDoc() method is an asynchronous operation, so we need to use await to wait for it to complete before accessing the newDocRef object.
Example of setDoc()
Here’s an example of using the setDoc() method to add or update a document in a Firestore collection in Firebase version 9
In this example, we first import the necessary Firebase modules and initialize the Firebase app with your Firebase config. Then, we get a Firestore instance using getFirestore().
Next, we define the collection where we want to add or update the document using collection(). We also define the document data as an object with name, email, and age fields.
Then, we define the document reference using doc(), passing in the collection and the ID of the document we want to add or update. Note that if the document ID does not exist in the collection, it will be created.
Finally, we use the setDoc() method to add or update the document in the collection. This method takes two arguments: the document reference and the document data. If the document already exists, setDoc() will update its contents with the new data. If the document does not exist, setDoc() will create it with the specified data.
Note that the setDoc() method is an asynchronous operation, so we need to use await to wait for it to complete before logging a success message.