0

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.

1 Answer 1

4

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());
Sign up to request clarification or add additional context in comments.

Comments

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.