Write, Update, and Delete data from Cloud Firestore
Explore how to manage data in Cloud Firestore by writing, updating, and deleting documents. Understand the use of setDoc, updateDoc, addDoc, and deleteDoc functions and how they handle data, including document creation, merging, and field deletion. Gain hands-on experience to confidently manipulate Firestore data in your web applications.
To carry out any operation on the Cloud Firestore database, we must create a reference to the specific path on our database. We covered how to create Firestore references in detail in the previous lesson. Feel free to head back for a refresher!
Write to the database
There are multiple ways to write to the Cloud Firestore. The method used depends on the behavior we want for our application. Let’s discuss these methods.
Use the setDoc function
The setDoc function writes to the document specified by the path to which its reference points. This function takes a reference to the database document as its first parameter. Its second parameter is an object with key-value pairs. These pairs represent the data we want to write.
The setDoc function is imported from the firebase/firestore subpackage and returns a JavaScript promise that resolves when the data has been written successfully to the database. We can handle this using JavaScript’s async-awai syntax or a .then callback.
The setDoc function creates a new document at the specified location if one doesn’t exist and overwrites any existing document at the database location.
However, if we don’t want to overwrite the data at that location, the setDoc takes an optional, third parameter to merge the new data with the old:
The merge parameter allows the setDoc function to create a new document if one doesn’t exist and only replaces/updates the specified fields. For example, although the widget above writes to the same document we write to in the first widget—test@educative.io—the widget above only updates the task and duration fields in the document. The difficulty field defined previously remains untouched after the write operation.
Use the updateDoc function
The updateDoc function is an alternative to the setDoc function. We can use it to write to the database. This function is imported from the firebase/firestore database and works like the setDoc function with merge set to true:
Note: This function throws an error if the document path in the reference doesn’t already exist. Therefore, if you’re unsure about the document’s existence, it is advisable to use the
setDocfunction with themergeoption set totrue.
Use the addDoc function
There may be times when we prefer not to set the document ID ourselves. This is where the addDoc function comes into play. This function is imported from the firebase/firestore subpackage and creates a new document with a randomly-generated ID in the specified collection reference path.
The addDoc function takes a collection reference as its first parameter and an object with key-value pairs representing the data to be written as its second parameter:
At this point, our database will look something like the slides below. The newly-added document with an auto-generated ID can be seen on the second slide.
Although both the addDoc and setDoc functions look alike, there are a few key differences between them. As we know, the addDoc function can generate unique IDs for the document created while the setDoc function cannot. In addition, the addDoc function is called with a collection reference while the setDoc function is called with a document reference.
Delete a document
To delete a document on the Cloud Firestore database, we must use the deleteDoc function. This function is imported from the firebase/firestore database. As a parameter, it takes a reference to the document to be deleted.
The deleteDoc function returns a JavaScript promise that resolves when the document is deleted successfully from the database:
Note: Deleting a document only deletes the key-value pairs associated with the document but not the subcollections within it. The content inside its subcollections remain untouched.
Delete fields in a document
When we don’t want to delete the entire document, it’s also possible to delete specific fields in a document. We do this by calling the deleteField function as a value to the unwanted fields when updating the document:
Note: Using the
updateDocfunction to update the field will also work, as demonstrated above.
Practice exercise
Study the highlighted lines in the widget below to learn how to write and delete data from the Cloud Firestore database.
import React, { useState } from "react";
import { documentWrite } from "../helpers/firestore";
function AddTask() {
const [input, setInput] = useState({ task: "", difficulty: "easy" });
const handleChange = (e) => {
setInput((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}));
};
const handleSubmit = (e) => {
e.preventDefault();
let { task, difficulty } = input;
documentWrite(task, difficulty, setInput);
};
return (
<div className="task-form">
<div className="form-input">
<form onSubmit={handleSubmit}>
<input
name="task"
placeholder="Input task"
type="text"
onChange={handleChange}
value={input.task}
required
/>
<label htmlFor="task" className="label-name">
<span className="content-name">Task</span>
</label>
<br />
<select
name="difficulty"
id="difficulty"
onChange={handleChange}
value={input.difficulty}
required
>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</select>
<label htmlFor="difficulty" className="label-name">
<span className="content-name">Difficulty</span>
</label>
<div className="btn">
<button title="submit" aria-label="submit" type="submit">
Submit
</button>
</div>
</form>
</div>
</div>
);
}
export default AddTask;
Steps to perform
- Run the code and open the output on a new tab using your unique Educative link.
- Create new tasks and submit them to write to the database.
- Modify the
documentWritefunction on line 17 to use theupdateDocfunction to write data to the database. - Modify the
deleteDocumentfunction on line 9 to use thedeleteFieldfunction to delete thedifficultyfield from the document created. - Use the
addDocfunction to add new documents to the collection reference defined on line 7. - Check the Firestore section of the Firebase console to view the tasks. Note the different database entries after each function call.