Aditya Hadi
Aditya Hadi

Reputation: 384

Firestore SetOptions.mergeFields() not working as expected using POJO

I'm trying to update a specific field in a document using POJO, as written in the doc. I could use SetOptions.mergeFields(). But it's updating other fields with null instead of keeping the other fields (which excluded from mergeFields) untouched. Is it intended?

Here is my code :

UserModel userModel = new UserModel();
userModel.setStatus(0);
setTask = documentReferenceToUse.set(userModel, SetOptions.mergeFields("status"));

setTask.addOnSuccessListener(new OnSuccessListener<Void>()
{
    @Override
    public void onSuccess(Void aVoid)
    {
        if (!emitter.isDisposed())
        {
            emitter.onComplete();
        }
    }
}).addOnFailureListener(new OnFailureListener()
{
    @Override
    public void onFailure(@NonNull Exception e)
    {
        if (!emitter.isDisposed())
        {
            emitter.onError(e);
        }
    }
});

And here is my document structure : document structure

[Solved] Turned out the issue came from my Firebase wrapper code. So there is no actual problem on the Firebase SDL side.

Upvotes: 1

Views: 3284

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138989

Edit: After taking another closer look at your code, I found that you need to change this line of code:

setTask = documentReferenceToUse.set(model, SetOptions.mergeFields("status"));

with:

setTask = documentReferenceToUse.set(userModel, SetOptions.mergeFields("status"));

You are passing as the first argument, not the object that you have just created but another one. So, the correct object that must be used is: userModel.

You can also use another approach, by getting that entire object from the database. Having the object, you can use setters to change the value of the fileds beneath it. After you have used the setters, you can use set() method directly on the reference to add the object the database.

documentReferenceToUse.set(userModelFromDatabase);

You can also use a Map in order to make an update:

Map<String, Object> map = new HashMap<>();
map.put("status", 0);
documentReferenceToUse.update(map);

Upvotes: 2

Related Questions