Home > OS >  Firebase Function onCreate add to new collection works, but update does not
Firebase Function onCreate add to new collection works, but update does not

Time:01-28

I have this onCreate Trigger, I am using it to aggregate and add record or update record. First it takes minutes to add the record and then the update never runs just keeps adding, not sure why my query is not bringing back a record to update.

Any suggestion would be great.

exports.updateTotals = functions.runWith({tinmeoutSeconds: 540})
    .firestore.document("user/{userID}/CompletedTasks/{messageId}")
    .onCreate(async (snap, context) => {
      const mycompleted = snap.data();
      const myuserid = context.params.userID;
      console.log("USER: " myuserid);
      const mygroup = mycompleted.groupRef;
      const myuser = mycompleted.userRef;
      const newPoints = mycompleted.pointsEarned;
      console.log("POINTS: " newPoints);
      const data = {
        groupRef: mygroup,
        userRef: myuser,
        pointsTotal: newPoints,
      };
      const mytotalsref = db.collection("TaskPointsTotals")
          .where("groupRef", "==", mygroup)
          .where("userRef", "==", myuser);
      const o = {};
      await mytotalsref.get().then(async function(thisDoc) {
        console.log("NEW POINTS: " thisDoc.pointsTotal);
        const newTotalPoints = thisDoc.pointsTotal   newPoints;
        console.log("NEW TOTAL: " newTotalPoints);
        if (thisDoc.exists) {
          console.log("MYDOC: " thisDoc.id);
          o.pointsTotal = newTotalPoints;
          await mytotalsref.update(o);
        } else {
          console.log("ADDING DOCUMENT");
          await db.collection("TaskPointsTotals").doc().set(data);
        }
      });
    });

CodePudding user response:

You are experiencing this behavior because while querying for updates you are getting more than 1 document and you are using thisDoc.exists on more than one document. If you have used typescript this could have been catched while writing the code.

So for the update query, if you are confident that only unique documents exist with those filters then here’s the updated code that I have recreated using in my environment.

functions/index.ts :

exports.updateTotals = functions.runWith({timeoutSeconds: 540})
    .firestore.document("user/{userId}/CompletedTasks/{messageId}")
    .onCreate(async (snap, context) => {
      const mycompleted = snap.data();
      const myuserid = context.params.userID;
      console.log("USER: " myuserid);
      const mygroup = mycompleted.groupRef;
      const myuser = mycompleted.userRef;
      const newPoints = mycompleted.pointsEarned;
      console.log("POINTS: " newPoints);
      const data = {
        groupRef: mygroup,
        userRef: myuser,
        pointsTotal: newPoints,
      };
      const mytotalsref = admin.firestore()
          .collection("TaskPointsTotals")
          .where("groupRef", "==", mygroup)
          .where("userRef", "==", myuser);
      await mytotalsref.get().then(async function(thisDoc) {
        if (!thisDoc.empty) { // check if the snapshot is empty or not
          const doc = thisDoc.docs[0];
          if(doc.exists){
            const newTotalPoints = doc.data()?.pointsTotal   newPoints;
            const id = doc.id;
            await db.collection("TaskPointsTotals").doc(id).update({pointsTotal: newTotalPoints});
          }
        } else {
          await db.collection("TaskPointsTotals").doc().set(data);
        }
      });
    });

For more information about QuerySnapshot methods check this docs

  • Related