Last active
October 21, 2021 03:41
-
-
Save ilhamsj/0c4be940069ae2d9c5132e9d52fded9b to your computer and use it in GitHub Desktop.
CRUD Firebase Firestore 9.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { getFirestore, collection, addDoc, getDocs, doc, getDoc, query, where, updateDoc, | |
deleteField, deleteDoc } = require('firebase/firestore') | |
initializeApp({ | |
apiKey: "", | |
authDomain: "", | |
projectId: "", | |
storageBucket: "", | |
messagingSenderId: "", | |
appId: "" | |
}); | |
const db = getFirestore() | |
const store = async (user) => { | |
try { | |
const result = await addDoc(collection(db, "users"), user); | |
console.log(result.id) | |
} catch (error) { | |
console.log('Failed to store data') | |
console.log({ error }) | |
} | |
} | |
const list = async () => { | |
try { | |
const result = await getDocs(collection(db, "users")); | |
result.forEach(val => { | |
console.log({ ...{ id: val.id, ...val.data() } }) | |
}) | |
} catch (error) { | |
console.log('Failed to store data') | |
console.log({ error }) | |
} | |
} | |
const findById = async (param) => { | |
const result = await getDoc(doc(db, "users", param)); | |
if (result.exists()) { | |
console.log(result.data()) | |
return result.data() | |
} else { | |
console.log("Data you're looking does not found!") | |
return "Data you're looking does not found!" | |
} | |
} | |
const findByName = async (firstName) => { | |
try { | |
const q = query(collection(db, "users"), where("first", "==", firstName)); | |
const result = await getDocs(q) | |
result.forEach(val => { | |
console.log({ id: val.id, ...val.data() }) | |
}) | |
} catch (error) { | |
console.log('Failed to store data') | |
console.log({ error }) | |
} | |
} | |
const deleteById = async (param) => { | |
const query = await deleteDoc(doc(db, "users", param)); | |
console.log('success'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment