Trying to create an if statement for the 'one' and 'two' functions, however when i am creating it i can't seem to make the statement run for each document. So i took it out and ran them buy them selves and they both work fine right now, but not sure how to wrap it in a condition for it to loop through each document in a collection .
any tips or pointers will be massively appreciated
thanks
const {
initializeApp,
applicationDefault,
cert,
} = require("firebase-admin/app");
const {
getFirestore,
Timestamp,
FieldValue,
} = require("firebase-admin/firestore");
const firebaseConfig = {
xxxx,
};
const serviceAccount = require("xxxxxx.json");
initializeApp({
credential: cert(serviceAccount),
});
const db = getFirestore();
async function one() {
const foodRef = db.collection("xxxxx");
const snapshot = await foodRef.where("item", "==", 2).get();
if (snapshot.empty) {
console.log("No matching documents.");
}
snapshot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
const res = doc.ref.set(
{
fatIntake: "50",
},
{ merge: true }
);
});
}
async function two() {
const foodRef = db.collection("xxxxxx");
const snapshot = await foodRef.where("item", "==", 1).get();
if (snapshot.empty) {
console.log("No matching documents.");
}
snapshot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
const res = doc.ref.set(
{
fatIntake: "10",
},
{ merge: true }
);
});
}
one();
two();
It seems like you have wrong if condition
In function one you put the following if statement
const snapshot = await foodRef.where("item", "==", 2).get();
You put item == 2 instead of item == 1. No mistake in the condition but the logic I suppose. Atleast what I think is the mistake. And the same problem is with function two
Also, confirm the field name item. This should exactly match the name in firestore, and it shouldn't be inside any other sub map.
If that is not the case and not what you asked then please elaborate more and precisely what your problem is.
The syntax and call to the if statement is correct. Actualy it is a query not an if statement. so, your query is syntatically correct.