Firebase - How can i get data from reference? - javascript

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?

Related

Why error Expected first argument to collection() to be a CollectionReference

I am getting the following error when trying to get all documents from a collection in Firestore using firebase admin SDK:
[nuxt] [request error] Expected first argument to collection() to be a
CollectionReference, a DocumentReference or FirebaseFirestore
I am testing via a simple console.log:
/server/api/posts.js:
import { firestore } from '../utils/firebase'
import { collection, getDocs } from 'firebase/firestore'
export default defineEventHandler(async (event) => {
const colRef = collection(firestore, 'posts')
console.log(colRef)
})
Here is how I am initializing firestore:
/server/utils/firebase.js:
import { initializeApp, cert } from 'firebase-admin/app'
import { getFirestore } from 'firebase-admin/firestore'
import serviceAccount from '../../service-account.json'
export const app = initializeApp({
credential: cert(serviceAccount)
})
export const firestore = getFirestore()
Note: The following code works on the server-side and I am able to get a document back, but for some reason I can't use the collection() like in the above example.
import { firestore } from '../utils/firebase'
export default defineEventHandler(async (event) => {
const ref = firestore.doc(`animals/dog`)
const snapshot = await ref.get()
const data = snapshot.data()
console.log(data)
// return {
// data
// }
})
Also, if I run the collection() function on the client side, I can successfully retrieve the posts. I just can't figure out why it won't work server-side.
Anyone know why I get the above error?
None of the server code you have shared align to such an error message. The error indicates that you are calling .get() or .onSnapshot() with something that is not a DocumentReference or a CollectionReference.
Note: collection() and doc() are functions that return References. They don't actually communicate to the FS service...a Reference is (essentially) a string such as `/posts' or '/posts/1234567'
So, somewhere in your code, you need to find where it is hitting the above error and either share it here or understand why what you are calling it on is not a valid CollectionReference or DocumentReference.

Firebase Function query and update a single Firestore document

I am trying to update a user's firestore doc from a Firebase Function using a query, and having issues getting it to work. My Function code is the following:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
/**
* A webhook handler function for the relevant Stripe events.
*/
// Here would be the function that calls updatePlan and passes it the customer email,
// I've omitted it to simplify the snippet
const updatePlan = async (customerEmail) => {
await admin.firestore()
.collection('users').where('email', '==', customerEmail).get()
.then((doc) => {
const ref = doc.ref;
ref.update({ 'purchasedTemplateOne': true });
});
};
I'm getting the following error in the firebase logs when the query is run:
Exception from a finished function: TypeError: Cannot read properties of undefined (reading 'update')
Any help regarding what I may be doing wrong or suggestions on how I could achieve this would be greatly appreciated, Thank you in advance!
Update:
I was able to solve my problem with more understanding of Firestore Queries:
const updatePlan = (customerEmail) => {
const customerQuery = admin.firestore().collection("users").where("email", "==", customerEmail)
customerQuery.get().then(querySnapshot => {
if (!querySnapshot.empty) {
// Get just the one customer/user document
const snapshot = querySnapshot.docs[0]
// Reference of customer/user doc
const documentRef = snapshot.ref
documentRef.update({ 'purchasedTemplateOne': true })
functions.logger.log("User Document Updated:", documentRef);
}
else {
functions.logger.log("User Document Does Not Exist");
}
})
};
The error message is telling you that doc.ref is undefined. There is no property ref on the object doc.
This is probably because you misunderstand the object that results from a Firestore query. Even if you are expecting a single document, a filtered query can return zero or more documents. Those documents are always represented in an object of type QuerySnapshot. That's what doc actually is - a QuerySnapshot - so you need to treat it as such.
Perhaps you should check the size of the result set before you access the docs array to see what's returned by the query. This is covered in the documentation.

is there any way to find a document from firebase firestore with the query of where

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

Valid way to delete a doc from firebase

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).

How to get a Subcollection inside a Collection in Firestore Web Version 9 (Modular)?

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());
});
});

Categories