android – How to add to array and create document if it doesn't exist in Firestore?-ThrowExceptions

Exception or error:

I’d like to make a call to Firestore to add to an array in a document. I can do this as follows:

document.update(someField, FieldValue.arrayUnion(someArrayElement))

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.

How to solve:

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());

Leave a Reply

Your email address will not be published. Required fields are marked *