0

Function executes when a write is made in collection logs, it checks if doc exists in collection totals. If doc exists it is trying to update number object with number+1 at [0] of array.

Here is my code:

...//some code
var washingtonRef = admin.firestore().collection('totals').doc(entryDate_show);
        washingtonRef.get().then((doc: any)=> {
          if (doc.exists) {
            console.log("doc found");
  console.log("Document data:", doc.data());
  washingtonRef.update({
    [auth_ID]: admin.firestore.FieldValue.arrayUnion(
      { number: doc.data().number+1,  // here it is trying to do +1
        fullname: fullname, 
        authid: auth_ID },
      )
  });
...//some code

Problem: It is not working as expected

In array, it is adding new object [1] with number : NaN

Expected behaviour: number : 2 at [0]

Attaching pic of the console:

enter image description here

1 Answer 1

1

FieldValue.arrayUnion() adds a new element to an array field. That's why you're seeing a new object.

Firestore provides no update operation that uses the index of an array item to modify it. If you want to update an item in an array by index, you have to read the document, modify the array in memory, then update the array field back to the document.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you guide me through example if possible. I know the array name here, it will also be fine if it deletes old one and overwrites with number+1 which I was expecting to happen.
I think the documentation is fairly clear about reading a document and updating it. All you have to do is modify the array in memory before you perform the update.
unable to get that array's number value, trying like this doc.data().auth_ID[0].number; but in functions log i see error doc.data().auth_ID[0].number;
That sounds like a new, different problem that you could explain with detail in a new post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.