所以我想在Firebase云功能中从Firebase实时数据库中获取数据。
我的数据库结构:
我的代码:
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.
}
顺便说一下,我在VSCODE中使用打字稿。
输出始终是未定义的。为什么?路径正确。我尝试了类似问题的所有方法,但没有帮助我。
该函数是ASYNC,我必须在其他功能中使用获取的值,所以我不想在这里使用return语句。可以吗?
答案 0 :(得分:1)
更改此:
usernameFetched = snapshot.val().username
对此:
usernameFetched = snapshot.val()
在您的路径中,您已经在使用ref(/Agent/${userUID}/username)
的{{1}}节点。因此,获取值所需要做的就是在username
上调用.val()
。