-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase-practice.js
More file actions
141 lines (123 loc) · 3.63 KB
/
firebase-practice.js
File metadata and controls
141 lines (123 loc) · 3.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
const { initializeApp } = require("firebase/app");
const {
getFirestore,
addDoc,
setDoc,
doc,
getDoc,
getDocs,
writeBatch,
collection,
} = require("firebase/firestore");
require("dotenv").config();
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
measurementId: process.env.FIREBASE_MEASUREMENT_ID,
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const cityLA = {
name: "Los Angeles",
state: "CA",
country: "USA",
};
const citySF = {
name: "San Francisco",
state: "CA",
country: "USA",
};
/**
* Create a new collection and add the first document.
* Method 1: addDoc() - Add a new document with a unique ID generated by Firestore
* Method 2: setDoc() - Add a new document with a specific ID (preferred)
*/
// // Method 1: Add a new document with a unique ID generated by Firestore - If the document already exists, it will create a new one because the IDs are unique.
// addDoc(collection(db, "cities"), citySF).then((docRef) => {
// console.log("Document written with ID: ", docRef.id);
// });
// // Method 2: Add a new document with a specific ID - If the ID already exists, it will be overwritten
// setDoc(doc(db, "cities", "LA"), cityLA).then(() => {
// console.log("Document written with ID: LA");
// });
// Retrieve the Cities collection
const citiesRef = collection(db, "cities");
getDocs(citiesRef)
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data().name}`);
});
})
.catch((error) => {
console.error("Error getting documents: ", error);
});
// Retrieve the LA document based on its ID
const laRef = doc(db, "cities", "LA");
getDoc(laRef)
.then((docSnap) => {
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
console.log("No such document!");
}
})
.catch((error) => {
console.error("Error getting document:", error);
});
// Update the LA document - Add a a new field and merge it with the existing data
setDoc(laRef, { population: 4000000 }, { merge: true })
.then(() => {
console.log("Document successfully updated!");
})
.catch((error) => {
console.error("Error updating document:", error);
});
// Add 2 more cities to the cities collection
const twoCities = [
{
name: "New York",
state: "NY",
country: "USA",
},
{
name: "London",
country: "UK",
},
];
// Use batch writes to add multiple documents
const batchWrites = writeBatch(db);
twoCities.forEach((city) => {
// Create a new reference for each city
const newCityRef = doc(citiesRef, city.name);
// Add the city to the batch
batchWrites.set(newCityRef, city);
});
// Access London ref and add population field
const londonRef = doc(citiesRef, "London");
batchWrites.update(londonRef, { population: 9000000 });
// Access LA ref and delete the population field
batchWrites.update(laRef, {
population: null,
});
// Commit the batch
batchWrites
.commit()
.then(() => {
console.log("Batch write successful!");
})
.catch((error) => {
console.error("Error writing batch:", error);
});
// Change LA to Los Angeles
getDoc(laRef).then((docSnap) => {
const oldData = docSnap.data();
const updatedData = { ...oldData, name: "Los Angeles" };
// Create a new document with the updated data
setDoc(citiesRef, updatedData).then(() => {
console.log("Document updated successfully!");
});
});