0

So I want to fetch data from my firebase realtime database in a firebase cloud function.

My Database structure:

Database

My code:

let usernameFetched: string
const snapshot = await admin.database().ref(`/Agent/${userUID}/username`).once("value")
usernameFetched = snapshot.val().username
console.log(`${usernameFetched}`)

return res.status(200).send({ 
    method: 'sendMessage',
    chat_id,
    text: `Your username is ${usernameFetched}) 
    //This returns a message to user via a telegram bot.
}

I'm using typescript in VSCODE by the way.

The output is always UNDEFINED. Why? The path is correct. I tried all the ways from similar question but didn't helped me.

The function is ASYNC and I have to use the fetched value in other fucntions so I don't want to use return statement here. Any way?

4
  • Please edit the question to show the complete, minimal code of the function that doesn't work the way you expect (not just a few lines). Also include a screenshot or some other detailed description of your database contents so that we can check that it's actually correct. stackoverflow.com/help/minimal-reproducible-example Commented Apr 13, 2020 at 15:18
  • @DougStevenson please have a look. That part only is related to fetching data from database. Rest of the code is to get userUID from User input. Everything runs fine except for the database returns UNDEFINED. 100001 is one of the UID and commandFn is use input command. Fetch means get data from database Commented Apr 13, 2020 at 15:22
  • That's still not the complete code of the function, nor can we see the contents of the database. Please edit your function down to just the code necessary to make the query, so that anyone can easy see what all is happening and reproduce the issue. There could be other things going on - we just can't see. Commented Apr 13, 2020 at 15:25
  • @DougStevenson done .. please let me know i am unable to retrieve data from database Commented Apr 13, 2020 at 15:37

1 Answer 1

1

Change this:

usernameFetched = snapshot.val().username

into this:

usernameFetched = snapshot.val()

In your path, you are already using ref(/Agent/${userUID}/username) the username node. Therefore all you have to do to get the value is call .val() on snapshot.

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

Comments

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.