0

I have a problem with updating certain properties of an array of objects in a real-time database in Firebase.

My object looks like the following (see picture).

Now I want to update the IsComing property of the second participant object.

enter image description here

At the moment I use the updateIsComming() function, but this is not very convincing, because I have to rewrite the whole object.

 function updateIsComming() {
   
    const db = getDatabase();
    update(ref(db, " your_path/EventModel/" + modelkey ), {
      Location: "London",
      Participants: [
        { Name: "Bella2", IsComming: "true" },
        { Name: "Tom", IsComing: "true" },
      ],
    });

Instead, I just want to reference the specific prop from that array. For example

Participant[1].IsComming = false;

Is there any way I can access a specific array of an object directly.

1 Answer 1

1

Arrays as a data structure are not recommended in Firebase Realtime Database. To learn why, I recommend reading Best Practices: Arrays in Firebase.

One of the reasons for this is that you need to read the array to determine the index of the item to update. The pattern is:

  1. Read the array from the database.
  2. Update the necessary item(s) in the array in your application code.
  3. Write the updated array back to the database.

As you already discovered, this is not ideal. As is common on NoSQL databases, consider an alternative data structure that better suits the use-case.

In this case, an alternative data structure to consider is:

Participants: {
  "Bella2": true,
  "Tom": true
}

In there, we use the name of the participant as the key which means:

  • Each participant can be present in the object only once, because keys in an object are by definition unique.
  • You can now update a user's status by their name with: update(db, "your_path/EventModel/" + modelkey + "/Participants/Tom", false).
Sign up to request clarification or add additional context in comments.

3 Comments

What if my participants have more than two properties, for example Name, IsComing, Phonenumer, ... ect. In this case, what would be a better data structure?
In that case the structure would look like that Participants: { Bella2: { IsComing: "true", PhoneNumber: "12345" }, Tom: { IsComing: "false", PhoneNumber: "123456" }, } But how can I than update the user's status?
Also what if i have to participants with the same name? In that case its better use an individualt key right?

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.