0

i m new in firebase and i m trying to get data from firebase database

Database structure : enter image description here

JS Code :

const userAnswersRef = admin.database().ref('/ChatbotProj/answers').child(userId);

return userAnswersRef.once('value')
  .then((dataSnapshot1) => {
    console.log("Fetching successed.");
    if (!dataSnapshot1.exists()) {
      return {}
    }
    var answers = dataSnapshot1.val();
    delete answers.lastQuestionId;
    return answers;
  });
};

I'm trying to get answers from the database. The problem is that the code return null when I execute dataSnapshot1.val(); even though that answers is not null

Can anyone help me ? Thanks

4
  • 1
    Your code seems correct. Are You sure that userId is not undefined or not null? Commented Feb 5, 2019 at 21:38
  • I don't see promise api from official manual: firebase.google.com/docs/database/admin/retrieve-data, so try this: userAnswersRef.once('value', snapshot => { console.log(snapshot.val()); }) Commented Feb 5, 2019 at 21:40
  • yess ! i even tried it with admin.database().ref('/ChatbotProj/answers/2042392955837498') and it didn't work Commented Feb 5, 2019 at 21:41
  • try to do it as in manual: firebase.google.com/docs/database/admin/retrieve-data Commented Feb 5, 2019 at 21:43

1 Answer 1

1

After answers you need to include "/", otherwise the resulting path would look like,

/ChatbotProj/answers12345uid

instead of,

/ChatbotProj/answers/12345uid

Set it like the example below,

const userAnswersRef = admin.database().ref('/ChatbotProj/answers/').child(userId);

Or, as I prefer to do it,

const userAnswersRef = admin.database().ref("ChatbotProj").child("answers").child(userId);
Sign up to request clarification or add additional context in comments.

3 Comments

I ve changed it and i still get the same result :/
What does it say in your log? Have you set the rules in the firebase console to allow you to read or write from the database? See the link here for Firebase documentation on rules. firebase.google.com/docs/database/security
THANK YOUUU ! it was the rules !

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.