Wiktor
Wiktor

Reputation: 925

Firestore SetOptions.mergeFields doesn't work

I'm trying to use .set on my document to set 2 values inside it, but it gives me this error

Field 'friendRequests' is specified in your field mask but not in your input data.

Error is triggered by this line in my code:

mCollRef.document(documentID).set(tempUser, SetOptions.mergeFields(fieldsToUpdate))

Everything works fine when i'm not using SetOptions, just mCollRef.document(documentID).set(tempUser)

What did i do wrong here?

My Code here:

mCollRef.whereEqualTo("userID", clickedUserID)
  .get()
  .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
     @Override
     public void onComplete(@NonNull Task<QuerySnapshot> task) {

     if(task.isSuccessful()) {

       List<String> fieldsToUpdate = Arrays.asList("friendRequests", "friends");

       for(QueryDocumentSnapshot document : task.getResult()) {

         User tempUser = document.toObject(User.class);

         tempUser.updateFriends(mUsersName, mUsersID, 1);
         tempUser.updateFriendRequests(myNoDotEmail, 2);
         String friendName = tempUser.getUserName();
         String documentID = document.getId();

         mCollRef.document(documentID).set(tempUser, SetOptions.mergeFields(fieldsToUpdate))
           .addOnSuccessListener(new OnSuccessListener<Void>() {
              @Override
              public void onSuccess(Void aVoid) {

                Toast.makeText(FriendsActivity.this, "Friend Added", Toast.LENGTH_SHORT).show();

              }).addOnFailureListener(new OnFailureListener() {
               @Override
               public void onFailure(@NonNull Exception e) {

                  Toast.makeText(FriendsActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
 });

It's worth pointing out that sometimes it works, like 1/10 it'll work just for no reason whatsoever and other 9 times it just doesn't

Upvotes: 2

Views: 980

Answers (1)

Wiktor
Wiktor

Reputation: 925

So, turns out that error was caused by my code few lines above SetOptions call:

enter image description here

As you can see above, field friendRequests isn't empty, but i'm setting it empty with this code from the question tempUser.updateFriendRequests(myNoDotEmail, 2); and that when it shows an error. Everything works when there are 2 or more friendRequests and i delete one of them, not leaving field completely empty.

Turns out SetOptions.mergeFields can't be called to set nested maps inside documents to empty maps.

Upvotes: 1

Related Questions