1
votes

I've been trying to update specific fields in a firebase document but for some reason, it does not get uploaded even though the cloud function gets triggered and performs an upload on the document, the value of the fields never gets uploaded.

The trigger function functions whenever any field is updated in "client details", then it gets the new field values. A reference is then created on the uploaded document in order to access an array to be iterated.

The document and document id are then passed to a function that iterates through each key: value pair in the updated document and then updates the fields with the same key in a different document.

Everything works without any error but the field values are never updated.


exports.rebuildFormTriggerClientDetails = functions.firestore.
document('clientDetails/{details}').onUpdate((change)  => {

  const afterDoc = change.after.data();
  const documentId = change.after.id

  if (afterDoc)

  {

    let docUsers = db.collection("clientDetails").doc(documentId);

    let caseArray: Array<string>;
    caseArray = afterDoc.CaseRefArray;

    for (var valCase of caseArray) {
      console.log(valCase); 
      console.log(documentId);

        createObjectDocument(docUsers,valCase);

    }

  }

  return Promise
});


function createObjectDocument(document: any, caseNumber: String)

{
  document.get().then(function(doc: any) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
        for (let [key, value] of Object.entries(doc.data())) {
          console.log(`${key}: ${value}`);
         if (key != "CaseRefArray")
         {

          db.collection("casesToExport").doc(caseNumber).update({key : value });
         }
        }
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error: any) {
    console.log("Error getting document:", error);
});


  [1]: https://i.stack.imgur.com/duhkq.png
1
You're ignoring the promise returned by update(). Your main function needs to return a promise that resolves only after all the other async work is complete. return Promise doesn't do that.Doug Stevenson

1 Answers

1
votes

Try to resolve your cloud function instead of returning a promise.

exports.rebuildFormTriggerClientDetails = functions.firestore.
document('clientDetails/{details}').onUpdate((change)  => {

  const afterDoc = change.after.data();
  const documentId = change.after.id

  if (afterDoc)

  {

    let docUsers = db.collection("clientDetails").doc(documentId);

    let caseArray: Array<string>;
    caseArray = afterDoc.CaseRefArray;

    for (var valCase of caseArray) {
      console.log(valCase); 
      console.log(documentId);

        createObjectDocument(docUsers,valCase);
    }
  }
}).then(() => {
   console.log("Successfully updated document!");
}).catch((error) => {
   console.error("Error updating document: ", error);
});