Firebase Firestore doesn't let me save new String to array via Cloud Function

Viewed 317

I'm trying to save a new String value to an Array in a document in Firebase Firestore via Cloud Function, this is the Source Code

Note: values.raffleId is a String

exports.onRaffleSignupCreate = functions.firestore
.document("posts/{postId}/raffleSignups/{signupId}")
.onCreate(async (snapshot, context) => {
  const values = snapshot.data();
  console.log(values.raffleId);
  db.collection("users")
      .doc(values.userId)
      .update({"signUps": admin
          .firestore
          .FieldValue
          .arrayUnion([values.raffleId])});
});

It gives me this error:

onRaffleSignupCreate
Error: Element at index 0 is not a valid array element. Nested arrays are not supported. at validateArrayElement (/workspace/node_modules/@google-cloud/firestore/build/src/field-value.js:427:15) at ArrayUnionTransform.validate (/workspace/node_modules/@google-cloud/firestore/build/src/field-value.js:354:13) at /workspace/node_modules/@google-cloud/firestore/build/src/document.js:809:56 at Map.forEach (<anonymous>) at DocumentTransform.validate (/workspace/node_modules/@google-cloud/firestore/build/src/document.js:809:25) at WriteBatch.update (/workspace/node_modules/@google-cloud/firestore/build/src/write-batch.js:379:19) at DocumentReference.update (/workspace/node_modules/@google-cloud/firestore/build/src/reference.js:387:14) at /workspace/lib/index.js:14:10 at cloudFunction (/workspace/node_modules/firebase-functions/lib/cloud-functions.js:134:23) at /layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:199:28

Has anyone else encountered this problem and knows how to fix it?

1 Answers

As explained in the Admin SDK doc for FieldValue.arrayUnion, you should pass the element (or a list of elements) and not an Array.

So the following should work:

  db.collection("users")
      .doc(values.userId)
      .update({"signUps": admin
          .firestore
          .FieldValue
          .arrayUnion(values.raffleId)});

Worth to note: if you have an array of elements that you want to pass to the method, use the spread syntax:

  const elemsToAdd = ['Banana', 'Apple'];

  db.collection("users")
      .doc(values.userId)
      .update({"signUps": admin
          .firestore
          .FieldValue
          .arrayUnion(...elemsToAdd)});
Related