Skip to content

Instantly share code, notes, and snippets.

@ilhamsj
Last active October 21, 2021 03:41
Show Gist options
  • Save ilhamsj/0c4be940069ae2d9c5132e9d52fded9b to your computer and use it in GitHub Desktop.
Save ilhamsj/0c4be940069ae2d9c5132e9d52fded9b to your computer and use it in GitHub Desktop.
CRUD Firebase Firestore 9.1
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