0

I'm trying to add data to an existing node i Firebase. But everytime I use UPDATE, SET or SETWITHPRIORITY, the existing data is removed. How do I add more ansers to my answer object?

{
   question:
   {
     title:"What's your favorite food?",
     answers:
     {
        answer:"pizza"
     }
   }
}

I have this right now...

quizzesRef.child(quizId + '/questions/question/answers').update({
answer:"sushi"});
1
  • Keys are unique in firebase, you cant have multiple "answer". You will have to give each a unique key. You could use push() for creating unique keys. Commented Jul 20, 2018 at 13:22

1 Answer 1

1

As André commented: keys under a given node must be unique. So if you update answers/answer it replaces the existing value of answers/answer. To add a new answer, it needs to have a new unique key, e.g. answers/answer2.

The common approach to generating unique keys is to use Firebase's built-in push() method. This generates a key that is chronological, guaranteed to be unique, and that will continue to work even if the app is offline. To add an answer with push you'd do:

quizzesRef.child(quizId + '/questions/question/answers').push("sushi");

Keys generated by push() will initially look overly complex. I recommend to resist the urge to use simpler keys. Firebase's push IDs are the idiomatic solution to many problems. By using them in your app, you prevent much lost time in development and debugging.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Frank for your input, but this means, that each time I add a new answer, I add an unique key to the input e.g. -LHqRaShhU20QYNb4a3u:{ answer:'Sushi' }
Correct. Isn't that precisely what you are trying to do? Otherwise I'm really confused about the use-case. Maybe you can update your question to show what you want the JSON to be after the update?
Thanks a million Frank, I’m new to this, so I just need to understand it.

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.