I am getting the following error:
TypeError: Cannot read properties of undefined (reading 'set').
I am trying to update the endTime in the script and i want to do it for each user then calculate the total amount of hours worked and update it in a field called 'totalTime'.
const {
initializeApp,
applicationDefault,
cert,
} = require("firebase-admin/app");
const {
getFirestore,
Timestamp,
FieldValue,
} = require("firebase-admin/firestore");
const firebaseConfig = {
xxxxxx
};
const serviceAccount = require("./fitness-69af3-firebase-adminsdk-c3hmg-c7fda98049.json");
initializeApp({
credential: cert(serviceAccount),
});
const db = getFirestore();
const age = "30";
async function main() {
const fitnessRef = db.collection("/food");
const snapshot = await fitnessRef
.where("role", "==", "junior")
.where("age", "==", age)
.get();
if (snapshot.empty) {
console.log("No matching documents.");
}
snapshot.forEach((doc) => {
let doc1 = doc.data();
let schedules = doc1.userInfo.schedule;
console.log(schedules);
const res = schedules.ref.set(
{
endTime: "17:30",
startTime: "09:00",
// totalTime: "{endTime - startTime}"
}, { merge: true }
);
});
}
main();
The ref property is a DocumentReference, and thus only exists on the full document, not on individual fields in there. So you will have to call doc.ref.update(...), with the field(s) you want to update.
Moreover, you can't update an individual item in an array in Firestore. You will have to read the entire array from the document, update the item in that array, and then write the entire array back to the database.