Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Last active April 15, 2024 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lejonmanen/6b17c7d5e4f056111ceb14703cfbcd34 to your computer and use it in GitHub Desktop.
Save lejonmanen/6b17c7d5e4f056111ceb14703cfbcd34 to your computer and use it in GitHub Desktop.
Firestore CRUD from static frontend 2024
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore, collection, addDoc, getDocs, getDoc, doc, updateDoc, deleteDoc } from 'firebase/firestore/lite'
// Get this from Firebase Console
import { firebaseConfig } from "./firebaseConfig.js";
// Initialize Firebase and get database
const app = initializeApp(firebaseConfig);
const db = getFirestore(app)
// Example: add one document to a collection (create the collection from Firebase console)
async function addFruit(name) {
await addDoc(fruitsCol, { name })
}
// Example: read all documents in the "fruits" collection
async function getFruits() {
const fruitsCol = collection(db, 'fruits')
const fruitSnapshot = await getDocs(fruitsCol)
const fruitList = fruitSnapshot.docs.map(doc => withId(doc))
return fruitList
}
// Use this if you don't have an id in the objects themselves
function withId(doc) {
let o = doc.data()
o.id = doc.id // "id" is the document reference
return o
}
// Use this when you know the id of the document you want
async function getFruitById(id) {
const docRef = doc(db, 'fruits', id)
const snapshot = await getDoc(docRef)
return snapshot.data()
}
// Use this when you want to search the collection
// Careful with string comparisions, 'hello' !== 'Hello'
async function getFruitsByValue(name) {
const q = query(fruitsCol, where('name', '==', name))
const querySnapshot = await getDocs(q)
querySnapshot.map(docRef => withId(docRef))
}
// When you know the id of document to change
async function editFruitById(name, id) {
const newData = { name }
await updateDoc(doc(db, 'fruits', id), newData)
}
// If you don't
async function editFruitByValue(name, newName) {
const q = query(fruitsCol, where('name', '==', name))
const querySnapshot = await getDocs(q)
const firstFound = querySnapshot.docs[0]
if( !firstFound ) { /* TODO: handle error */ }
const foundId = firstFound?.ref?.id
const newData = { name: newName }
await updateDoc(doc(db, 'fruits', foundId), newData)
}
// Delete documents matching a value
async function deleteByValue(name) {
const fruitsCol = collection(db, 'fruits')
const q = query(fruitsCol, where('name', '==', name))
const querySnapshot = await getDocs(q)
querySnapshot.forEach(d => {
const ref = doc(db, 'fruits', d.ref.id)
deleteDoc(ref)
})
}
// Export all your CRUD functions
export { getFruits, ... }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment