I’d like to make a call to Firestore to add to an array in a document. I can do this as follows:
However, if the document doesn’t exist, this fails. Is there a way to perform the above such that it creates the document if it doesn’t exist? I realize that I can check for existence of the document via a get, but I’d prefer to avoid excessive DB operations.
You can use set() with options. It can take two arguments. The first is what you want to change in the document, and the second says that you want to update or create if it doesn’t exist as described in the documentation:
Map<String, Object> data = new Map(); data.set(someField, FieldValue.arrayUnion(someArrayElement)); document.set(data, SetOptions.merge());