Back to snippets
firebase_firestore_quickstart_add_and_retrieve_documents.ts
typescriptInitializes Cloud Firestore, adds a new document with generated data, a
Agent Votes
0
0
firebase_firestore_quickstart_add_and_retrieve_documents.ts
1import { initializeApp } from "firebase/app";
2import { getFirestore, collection, addDoc, getDocs } from "firebase/firestore";
3
4// TODO: Replace the following with your app's Firebase project configuration
5// See: https://support.google.com/firebase/answer/7015592
6const firebaseConfig = {
7 apiKey: "YOUR_API_KEY",
8 authDomain: "YOUR_AUTH_DOMAIN",
9 projectId: "YOUR_PROJECT_ID",
10 storageBucket: "YOUR_STORAGE_BUCKET",
11 messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
12 appId: "YOUR_APP_ID"
13};
14
15// Initialize Firebase
16const app = initializeApp(firebaseConfig);
17
18// Initialize Cloud Firestore and get a reference to the service
19const db = getFirestore(app);
20
21async function runQuickstart() {
22 try {
23 // Add a new document with a generated ID
24 const docRef = await addDoc(collection(db, "users"), {
25 first: "Ada",
26 last: "Lovelace",
27 born: 1815
28 });
29 console.log("Document written with ID: ", docRef.id);
30
31 // Read data from the collection
32 const querySnapshot = await getDocs(collection(db, "users"));
33 querySnapshot.forEach((doc) => {
34 console.log(`${doc.id} => ${JSON.stringify(doc.data())}`);
35 });
36 } catch (e) {
37 console.error("Error adding/retrieving document: ", e);
38 }
39}
40
41runQuickstart();