DMur
DMur

Reputation: 661

Delete single value from Cloud Firestore Array

FirestoreScreenshot

I am trying to delete the single "m80KEXuYelOGutSLtQelQkIDj9H2" value from within my "players" array in Cloud Firestore.

Logs show that String findTeam is CoolTeam1 and String userId is m80KEXuYelOGutSLtQelQkIDj9H2

My code is:

DocumentReference docRef = db.collection("teams").document(findTeam);
docRef.update({"players":FieldValue.arrayRemove(userId)});

I'm getting "Unexpected token" in Android Studio for the { and the }) in the above.

Any ideas would be much appreciated?

I have also tried using dot notation as per below, this runs but does not delete the value:

db.collection("teams").document(findTeam).update("players." + userId, FieldValue.delete());

I have also tried using a Map update, this also runs and shows "Deleting player successful" in the Log. But the player is not removed in Firestore.

Map<String,Object> updates = new HashMap<>();
updates.put(userId, FieldValue.delete());

doc.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {

       if (task.isSuccessful()){
       Log.i(TAG, "Deleting player successful");
       }
       else{
       Log.i(TAG, "Deleting player NOT successful");
       }
      }
});```

Upvotes: 0

Views: 714

Answers (2)

DMur
DMur

Reputation: 661

Figured it out eventually...

Import the class:

import static com.google.firebase.firestore.FieldValue.arrayRemove;

Then use:

db.collection("teams").document(findTeam).update("players", arrayRemove(userId));

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317372

It looks like your first code sample with the curly braces is trying to use the JavaScript syntax for updating a document rather than the Java Android syntax. That's not going to work at all, obviously.

FieldValue.delete() is going to work at all for you either, since that's used for deleting an entire document field, not modifying an array. You will want to use FieldValue.arrayRemove() instead, as shown in the documentation. Be sure to use the Java Android syntax.

Try this instead:

db.collection("teams").document(findTeam).update("players",
    FieldValue.arrayRemove(userId));

Upvotes: 3

Related Questions