1

I want to update a document with a User object that I have, but I do not want the document to be created if it does not exist, and therefore I cannot use "DocumentReference.set" with "SetOptions.Merge()" (to my understanding).

However, according to this post (Difference between set with {merge: true} and update), "update" is actually the command I need. My problem is, it doesn't seem like update accepts a Java object.

I do not want to check whether or not the document exists myself, as this will result in an unnecessary read.

Is there any way around this?

Here is my code (I have removed success and failure listeners for simplicity):

    public void saveUser(User user)
    {
        CollectionReference collection = db.collection("users");

        String id = user.getId();
        if (id.equals(""))
        {
            collection.add(user);
        }
        else
        {
            // I need to ensure that the ID variable for my user corresponds
            // with an existing ID, as I do not want a new ID to be generated by 
            // my Java code (all IDs should be generated by Firestore auto-ID)
            collection.document(ID).set(user);
        }
    }
Gary Allen
  • 1,218
  • 1
  • 13
  • 28
  • Please edit the question to show the code you're working with and the document data that you want to update. It's hard to understand what you're trying to do. – Doug Stevenson Jul 24 '20 at 16:02
  • @DougStevenson done as requested – Gary Allen Jul 24 '20 at 16:37
  • It sounds like you have two separate problems here. One is how to update if you have an object in hand. The other is what to do if the document doesn't already exist. I'll address both issue in my answer. In the future, please make sure your question address a single issue at a time. – Doug Stevenson Jul 24 '20 at 16:43

1 Answers1

1

It sounds like you:

  1. Want to update an existing document
  2. Are unsure if it already exists
  3. Are unwilling to read the document to see if it exists

If this is the case, simply call update() and let it fail if the document doesn't exist. It won't crash your app. Simply attach an error listener to the task it returns, and decide what you want to do if it fails.

However you will need to construct a Map of fields and values to update using the source object you have. There are no workarounds for that.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441