Adding a Document to a Collection
To add a document to a collection, you can use the setDoc method. This method allows you to create a new document or overwrite an existing document.
Example: Adding a User
Let’s add a user to a users collection. Each user will have a name, email, and createdAt field.
import { doc, setDoc } from "firebase/firestore";
// Create a reference to the users collection
const userRef = doc(db, "users", "userId123");
// Set the user's data
await setDoc(userRef, {
name: "John Doe",
email: "john.doe@example.com",
createdAt: new Date().toISOString()
});
Explanation:This code snippet demonstrates how to add a document to a Firestore collection. It creates a reference to a document in the “users” collection with the ID “userId123” and then uses the `setDoc` method to set the user’s data, including name, email and the creation timestamp. If the document already exists, it will be overwritten with the new data.
Writing and Reading Data in Cloud Firestore
Cloud Firestore is a NoSQL document database built for automatic scaling, high performance, and ease of application development. In this article, we will explore how to write and read data in Cloud Firestore along with complete with detailed examples and. Whether you are a beginner or looking to refine your understanding, this guide will walk you through the basics in a straightforward, easy-to-understand manner.