0

I have a structure like this and in this I want to update the role of userId '2' to "Admin".

{
  "chats": {
    "chatThreadID": {
      "chatUsers": [
        {
          "userId": 1,
          "role": "Admin"
        },
        {
          "userId": 2,
          "role": "General"
        },
        {
          "userId": 3,
          "role": "General"
        }
      ]
    }
  }
}

I tried doing 'updateData'

"chatUsers": FieldValue.arrayRemove([oldUser.dictionary])

Then

"chatUsers": FieldValue.arrayUnion([updatedUser.dictionary])

This works, but is there any better way to do this?

1 Answer 1

2

What you're doing looks correct to me.

If you're looking to update a user with a single write operation, the most common alternative is to not store the users in an array field with their roles, but store the user+roles in a map field:

"chatUserRoles": {
  "1": "Admin",
  "2": "General",
  "3": "General"
}

With this structure, you can update a specific user with dot notation:

"chatUserRoles."+updatedUser.dictionary.userId: updatedUser.dictionary.role

Or as literal text:

"chatUserRoles.1": "General"
Sign up to request clarification or add additional context in comments.

2 Comments

How to use "chatUserRoles."+updatedUser.userId: updatedUser.role?
I updated the code in my answer to include the .dictionary that you're using, and also to show it without the variables. It's meant to be the replacement of your current line of code to update the document. If it isn't working for you, show what you tried and what the result was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.