import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const config = {
apiKey: "xxxx",
authDomain: "xxxx",
projectId: "xxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxx",
appId: "xxxx",
};
export const app = initializeApp(config);
export const db = getFirestore(app);
const collectionRef = collection(db, "users");
getDocs(collectionRef).then((snapshot) => {
snapshot.docs.forEach((doc) => {
console.log(doc.data());
});
});
const docRef = doc(db, "users", "G3OIFQ7qes9Rhc74XfRA");
// - OR
// const docRef = doc(db, "users/G3OIFQ7qes9Rhc74XfRA");
getDoc(docRef).then((snapshot) => {
console.log(snapshot.data());
});
const docSnap = await getDoc(docRef);
if(!docSnap.exists()) {
console.log("Document does not exist!");
}
const collectionRef = collection(db, "users");
const q = query(collectionRef, where("username", "==", "kingrayhan"));
const snapshot = await getDocs(q);
console.log(snapshot.docs[0].data());
// -- More query example
const stateQuery = query(citiesRef, where("state", "==", "CA"));
const populationQuery = query(citiesRef, where("population", "<", 100000));
const nameQuery = query(citiesRef, where("name", ">=", "San Francisco"));
Query operator
<
- less than<=
- less than or equal to==
- equal to>
- greater than>=
- greater than or equal to!=
- not equal toarray-contains
array-contains-any
in
not-in
const collectionRef = collection(db, "users");
const docRef = await addDoc(collectionRef, {
username: "johndoe",
avatar: "https://avatars0.githubusercontent.com/u/174825?v=4",
});
console.log(docRef.id);
const docRef = doc(db, "users", "user-id-custom");
// - OR
// const docRef = doc(db, "users/G3OIFQ7qes9Rhc74XfRA");
await setDoc(docRef, {
username: "kingrayhan",
avatar: "https://avatars0.githubusercontent.com/u/174825?v=4",
});
const docRef = doc(db, "users", "xj7lxm0OGObV91xn3tE0");
await deleteDoc(docRef);
const docRef = doc(db, "users", "AvPfqaJs4hCmqpk0RUjU");
// - OR
// const docRef = doc(db, "users/G3OIFQ7qes9Rhc74XfRA");
/**
* Update document
*/
await updateDoc(docRef, {
name: "Rayhan",
username: "rayhan",
});
/**
* Override the whole document
*/
await setDoc(docRef, {
x: 10,
});
const colRef = collection(db, "posts");
const q = query(colRef, limit(5))
const postsSnap = await getDocs(q)
const posts = postsSnap.docs.map((post) => post.data())
// -> console.log(posts)
const colRef = collection(db, "posts");
const q = query(colRef, limit(5), orderBy("createdAt", "desc"))
const postsSnap = await getDocs(q)
const posts = postsSnap.docs.map((post) => post.data())
// -> console.log(posts)