0

Question

I have a collection named Users with a field named friendEmails which is an array that contains Strings.

I have a document with friendEmails = {joe@gmail.com, dan@gmail.com}, and I want to append newEmails = {mat@gmail.com, sharon@gmail.com} to it.

Problem

The only options I know for this are:

  1. Reading the friendEmails array first, then adding the union of it and newEmails to the document.

  2. Iterating over the elements of newEmails (let's and each iteration doing: myCurrentDocumentReference.update(FieldValue.arrayUnion, singleStringElement);
    (Since FieldValue.arrayUnion only lets me pass comma-separated elements, and all I have is an array of elements).

These two options aren't good since the first requires an unnecessary read operation (unnecessary since FireStore seems to "know" how to append items to arrays), and the second requires many write operations.

The solution I'm looking for

I'd expect Firestore to give me the option to append an entire array, and not just single elements.

Something like this:

ArrayList<String> newEmails = Arrays.asList("mat@gmail.com", "sharon@gmail.com");

void appendNewArray() {
    FirebaseFirestore firestore = FirebaseFirestore.getInstance();
    firestore.collection("Users").document("userID").update("friendEmails", FieldValue.arrayUnion(newEmails));
}

Am I missing something? Wouldn't this be a sensible operation to expect?

How else could I go about performing this action, without all the unnecessary read/write operations?

Thanks!

Alon Emanuel
  • 172
  • 3
  • 10

1 Answers1

2

You can add multiple items to an array field like this using FieldValue.arrayUnion() as the value of a field update:

docRef.update("friendEmails", FieldValue.arrayUnion(email1, email2));

If you need to convert an ArrayList to an array for use with varargs arguments:

docRef.update("friendEmails", FieldValue.arrayUnion(
    newEmails.toArray(new String[newEmails.size()])
));
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • My problem is with "unpacking" my existing ```newEmails``` array to pass as arguments for arrayUnion. How would I go about it? – Alon Emanuel Oct 10 '20 at 17:57
  • Please edit the question to show the specific code you're working with, and clarify the question about what isn't working the way you expect with that code. – Doug Stevenson Oct 10 '20 at 18:04