I want to delete a game from my firestore collection, but i get error:
TypeError: doc is not a function
I am using the latest version of Firebase. What is the proper way to delete the doc?
import {where,query,deleteDoc,collection, doc, getDocs, getFirestore } from "firebase/firestore";
deleteGame(game) {
const db = getFirestore();
const q = query(collection(db, "history"), where("date", "==", game.date));
const doc = getDocs(q);
const quer = await getDocs(q);
quer.forEach((doc) =>
{
deleteDoc(doc(db, "history", doc.id));
});
}
According to firebase documentation for delete data you should indeed use
deleteDoc(doc(db, "history", doc.id));
But doc needs to be the function imported from firebase/firestore . You are rewriting the value of doc with the element from quer ( quer.forEach((doc) => ).
You also have const doc = getDocs(q); so you will need change the name of both doc variables in order to use the imported function inside the forEach callback.
Also keep in mind that this won't subcollections (if you have any - as specified in the docs).
Related
I've been struggling with Firestore queries.
This is my structure:
I'm simply trying to fetch data where any item of a set of categories belongs to any entry.
So, I'm doing something like it:
firebaseQuery(
entriesRef,
where("categories", "array-contains-any", ["link"])
where("date", ">=", "{SOME DATE BEFORE 01/01/2023}")
orderBy("date", "desc")
)
But result is always empty. Any idea of what could going on?
Thanks!
EDIT
Important information, I've made some tests and seems the getDocs(query) promise is never resolved or rejected (according to logs)
First I didn’t find any firebaseQuery in docs so I have recreated the setup from the provided code and just replaced the firebaseQuery with a query from the official firebase/firestore package.
Here’s the updated code :
import { collection, getDocs, orderBy, query, where } from "firebase/firestore";
import { db } from "./firebase.js";
const ref = collection(db, "entries");
const start = new Date();
console.log(start);
const q = query(
ref,
where("categories", "array-contains-any", ["link"]),
where("date", ">=", start),
orderBy("date", "desc")
);
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data().categories, doc.data().date.toDate());
});
I have a firebase firestore with some reference datatype.
It looks like this:
I Hope, this is the correct way.
Now when i get my user from firebase, i have this reference object with the id of it.
But if i call my function to get the doc, i get an error message:
First my function and how i call it:
export const getClubById = async (id: string) => {
const doc = collection(db, 'clubs', id)
return doc
}
const userData = dbUser.data()
const club = await getClubById(userData.selectedClub.id)
console.log('club', club)
And here the error message:
Uncaught (in promise) FirebaseError: Invalid collection reference. Collection references must have an odd number of segments, but clubs/vA7R94pX3bpHDsYIr6Ge has 2.
If you have the DocumentReference already then you can use getDoc() function to retrieve the document from Firestore as shown below:
import { getDoc, DocumentReference } from "firebase/firestore";
export const getClubById = async (clubDocRef: DocumentReference) => {
const clubSnapshot = await getDoc(clubDocRef);
return clubSnapshot.data();
}
// Pass the reference itself to the function instead of doc ID
const club = await getClubById(userData.selectedClub)
For the error in the question, to create a DocumentReference, if you have the document ID then you should doc() function instead of collection() that is used to create a CollectionReferencce as shown below:
const docRef = doc(db, 'clubs', clubID);
Also checkout: Firestore: What's the pattern for adding new data in Web v9?
I have a collection of tokens in which each document create with auto id but I store a tokenId in the document and now I want to search a single document which has specific tokenId
How can I implement where query in my this code
const docRef = doc(db , "tokens")
const data= await getDoc(docRef);
First, you should use collection() instead of doc() to create a CollectionReference. Then you can build the required Query using query() with where() as shown below:
import { collection, getDocs, query, where } from "firebase/firestore"
const colRef = collection(db , "tokens")
const qSnap = await getDocs(query(colRef, where("tokenId", "==", "TOKEN_VALUE")));
if (qSnap.size) {
const data = qSnap.docs[0].data();
} else {
console.log("No token found")
}
Also checkout:
Firestore: What's the pattern for adding new data in Web v9?
Perform simple and compound queries in Cloud Firestore
can some one explain how can i delete collection in firebase/firestore using v9 using reactjs
firestore()
.collection('rate')
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
doc.ref.delete();
});
this code i am using in v8 i need same thing in v9
const q = query(collection(db, `${udata.id}`));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.data());
});
already try this but this code only read data this can't allow me to delete so can some one tell me how to do it
There's a top-level function deleteDoc() to delete documents in using Modular SDK:
import { collection, query, getDocs, deleteDoc } from 'firebase/firestore';
const q = query(collection(db, `${udata.id}`));
const querySnapshot = await getDocs(q);
const deleteOps = [];
querySnapshot.forEach((doc) => {
deleteOps.push(deleteDoc(doc.ref));
});
Promise.all(deleteOps).then(() => console.log('documents deleted'))
You can use deleteDoc(), as documented here.
deleteDoc() takes a document reference, so you'll need to pass the reference from inside the forEach. In the forEach you're receiving a QueryDocumentSnapshot, so you just need to add a
deleteDoc(doc.ref);
I was using the chaining mode of the Firestore Web 8, but I'm in the way of updated it to Module 9 and have been a hard time trying to figure out how to get all the content of my subcollection (collection inside my collection).
My older function is like this and works fine:
function getInfo(doc_name) {
let infoDB = db
.collection("collection_name")
.doc(doc_name)
.collection("subcollection_name")
.get();
return alunoHistorico;
}
so with the module way I tried this code
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const docRef = doc(db, "collection_name", "doc_name");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
but the function doc() expects a even arguments (not counting the db argument) so if I try to use with 3 arguments like this, I get a error:
const docRef = doc(db, "collection_name", "doc_name", "subcollection_name");
to it work I have to pass the exactly document that is inside the subcollection
const docRef = doc(db, "collection_name", "doc_name", "subcollection_name", "sub_doc");
but it doesn't work for me because I have a list os docs inside the subcollection, that I want o retrieve.
So how can I get all my docs inside my subcollection?
Thanks to anyone who take the time.
You need to use collection() to get a CollectionReference instead of doc() which returns a DocumentReference:
const subColRef = collection(db, "collection_name", "doc_name", "subcollection_name");
// odd number of path segments to get a CollectionReference
// equivalent to:
// .collection("collection_name/doc_name/subcollection_name") in v8
// use getDocs() instead of getDoc() to fetch the collection
const qSnap = getDocs(subColRef)
console.log(qSnap.docs.map(d => ({id: d.id, ...d.data()})))
I wrote a detailed answer on difference between doc() and collection() (in V8 and V9) here:
Firestore: What's the pattern for adding new data in Web v9?
If someone want to get realtime updates of docs inside sub collection using onSnapshot in Modular Firebase V9, you can achieve this like:
import { db } from "./firebase";
import { onSnapshot, collection } from "#firebase/firestore";
let collectionRef = collection(db, "main_collection_id", "doc_id", "sub_collection_id");
onSnapshot(collectionRef, (querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log("Id: ", doc.id, "Data: ", doc.data());
});
});