Wafi_ck
Wafi_ck

Reputation: 1398

How to remove field from array in Firestore?

enter image description here

I want to remove a specific field (it's user id) from the array in Firestore.

I try:

 override fun unlikePost(postId: String) {
        FirebaseFirestore.getInstance().collection(postCollection)
            .document(postId).update("likeList", FieldValue.arrayRemove(FirebaseAuth.getInstance().uid))
    }

But when I do this my likeLIst in Firestore change to:

[]

Why unlikePost doesn't remove specific field but clear whole array and change to []?

Upvotes: 0

Views: 606

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 1

How to remove a field from an array in Firestore?

A call to:

.update("likeList", FieldValue.arrayRemove(FirebaseAuth.getInstance().uid))

Does indeed that. This means that you are removing the UID of the authenticated user from the "likeList" array. However, this doesn't mean that you are removing the array entirely from the document, hence that representation. The two brakes [] represent an empty array.

So how can you remove the entire array from the document? You might think that passing a null value, might do the trick, but it won't, since null is a supported data type in Firestore. So a call to:

.update("likeList", null)

It will lead to:

Firestore-root
   |
   --- posts (collection)
        |
        --- postId (document)
             |
             --- likeList: null (array)

If you want to get rid of the array entirely from the document, you should use a call to:

.update("likeList", FieldValue.delete())

In this way, your array will be deleted from the document no matter how many UIDs exist in the array.

Edit:

According to your last comment:

For example there is 5 UID in the array. I want to remove only a specific one. Now when I try to do that I clear the whole array.

Let's assume you have an array that contains two UIDs, one is "abc" and the second one is "xyz". The last one being the UID of the authenticated user. If you want to remove "abc", you should use a call to:

.update("likeList", FieldValue.arrayRemove("abc"))

If you want to remove the second one, you should use:

.update("likeList", FieldValue.arrayRemove("xyz"))

Or:

.update("likeList", FieldValue.arrayRemove(FirebaseAuth.getInstance().uid))

Because FirebaseAuth.getInstance().uid returns "xyz".

Upvotes: 2

Related Questions