Firebase obtaining multiple documents from a collection not working - javascript

I'm using a datepicker in a food ordering webpage, the date selected by the user is stored in a variable called dateSelected, then, the following function is used to get the data depending on the date they selected:
const q = query(collection(db, "cities"), where("capital", "==", true));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
However, nothing is logged in the console. If I only console log the querySnapshot, the result in the console is the following:
xu {_firestore: ka, _userDataWriter: ah, _snapshot: Fo, metadata: Du, query: Aa}
I tried this:
const q = query(collection(db, "/Dishes/All/Lunch"), where("dates", "==", dateSelected));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
});
console.log(doc.id, " => ", doc.data());
This line above appears to be the line that is not working
Here's an example of a date picked that matches the one in firebase and what is logged in the console after picking it:

dates is an array that will never be equal to a string. If you want to query all lunch documents where dates array contains a given date, then try using array-contains operator instead:
const q = query(collection(db, "/Dishes/All/Lunch"), where("dates", "array-contains", dateSelected));
const querySnapshot = await getDocs(q);
console.log(querySnapshot.size)

Related

Get the var value out of IF statement

I'm trying to do a comparison between user session email and an email in an array in firestore. That is, I want to search for the login email within the database and if any email is found, bring some information to the screen, such as name and surname.
I even managed to get inside the array and make this comparison, but I can't make the "var UserName" leave the { } of the IF
Can someone help me?
my code is:
const [data, setData] = useState([]);
const getUsers = () => {
firestore()
.collection("users")
.get()
.then((querySnapshot) => {
let userFirestore = [];
querySnapshot.forEach((doc) => {
const usuario = {
id: doc.id,
nome: doc.data().nome,
sobrenome: doc.data().sobrenome,
email: doc.data().email,
profissao: doc.data().profissao,
}
userFirestore.push(usuario);
});
userFirestore.forEach(function (item, indice, array) {
if (item.email === user.email){ //user.email brings the email of the logged in user
var nomeUsuario = item.nome
console.log(nomeUsuario) //UserName brings the result I expected
}
});
})
.catch((error) => console.log(error));
}
You can use a query to get a document with current user's email that instead of fetching the whole collection as shown below:
firestore()
.collection("users")
.where("email", "==", user.email)
.get().then((querySnapshot) => {
if (querySnapshot.empty) {
console.log("User not found")
return;
}
const user = querySnapshot.docs[0].data();
console.log(user)
})
Even better, if you use user's UID as the Firestore document ID (highly recommended), then you can get that single document by ID as shown below:
firestore()
.collection("users")
.doc(user.uid) // < user.uid must be defined
.get()
.then((snapshot) => {
console.log(snapshot.data())
})
When you fetch the whole collection, you are charged N read where N is total number of documents in the collection and it'll be slower as you are downloading plenty of data.

How to access a collection within a collection in Firestore database?

I'm trying to access the document data from bank_account_2, and the problem is that bank_account_2 that is a collection within a collection. Basically we have users>user1>bank_accounts>bank_account_2
But I didn't find a way to do this using the modular version 9 for websites. This is my code for now, does anyone have a solution? Thank you in advance!
//----Getting the user data------
import { doc, collection, getDocs, getDoc} from "https://www.gstatic.com/firebasejs/9.9.0/firebase-firestore.js";
import db from "./database.js"
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
As explained in the doc, you can use a "slash-separated path to a collection" as follows:
await getDocs(collection(db, "users/user1/bank_accounts"));
Of course you want the ID of the user doc to be variable. So you can either do:
const userId = "user1";
await getDocs(collection(db, "users/" + userId + "/bank_accounts"));
or, by using template literals;
const userId = "user1";
await getDocs(collection(db, `users/${userId}/bank_accounts`));
(Note that template literals are enclosed by backtick (`) characters instead of double or single quotes)
But you could also pass the different sub-collection path segments to the collection() method, like:
const userId = "user1";
await getDocs(collection(db, "users", userId, "bank_accounts"));
Moreover... you could even mix the two above approaches, as follows!
const userId = "user1";
await getDocs(collection(db, `users/${userId}`, "bank_accounts"));
or
const userId = "user1";
await getDocs(collection(db, "users", `${userId}/bank_accounts`));

Firestore query returns nothing

Here is the structure of the firestore database
ingredients->(doc name)-> ingredientName: "Apple"
I am trying to figure out the document name of the document with Apple in it but I keep running into an issue where nothing is returned.
async function getIngredientID(){
const q = query(collection(fsdb, 'ingredients'), where('ingredientName', '==', 'Apple'));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
}
there is nothing that comes out on the console. At one point I console logged the value of q and there was no document there. All of the StackOverflow answers have to do with Web version 8 but I am working with Web version 9.
I imagine you must have the imports, make sure you have them all correctly. Now import >>fsdb<< make sure to start cloud firestore and get a reference to the service, check that the where method is correct as well as the collection, i don't know what information it has when initializing firebase, it would be nice if you could send more information, if this information does not help you
import { collection, getDocs, query, where } from "firebase/firestore";
import { fsdb } from '../fb';
async function getIngredientID() {
try {
const q = query(
collection(fsdb, "ingredients"),
where("ingredientName", "==", "Apple")
);
const { docs } = await getDocs(q);
const data = docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
} catch (error) {
console.log(error);
}
}

delete collection firebase in v9

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

How to update field in firebase document?

Hello I want to update a field in a firebase document.
Right now , I am accessing the document collection like this
However I am having trouble setting teh shares field of the doc to shares+=1 ?
What am i doing wrong here in the set method?
const buyStock = async () => {
const q = await query(
collection(db, 'myStocks'),
where('ticker', '==', props.name)
);
const querySnapshot = await getDocs(q);
if (!querySnapshot.empty) {
// simply update the record
querySnapshot.forEach((doc) => {
doc.id.set({
shares: doc.id.data().shares+=1
})
// doc.data() is never undefined for query doc snapshots
console.log(doc, doc.id, ' => ', doc.data());
});
You're almost there. To update a document, you need a reference to that document. You can get this with:
querySnapshot.forEach((doc) => {
doc.ref.update({
shares: doc.data().shares+=1
})
});
You can also use the built-in atomic increment operator:
doc.ref.update({
shares: increment(1)
})
It looks like you are calling the set method on the 'id' field. Try to remove that. So just do
doc.set({
shares: doc.data().shares+=1
})
give that a shot. If that doesn't work, i'd try updating a document that is not part of a query snapshot.

Categories