1

我使用这个代码:从Cloud Functions中为Firebase读取数据?

exports.lotteryTickets = functions.database.ref('/lottery/ticketsneedstobeprocessed/{randomID}').onWrite(event => { 
    let ticketsBoughtByUser = event.data.val(); 

}) 

但ticketsBoughtByUser是不正确的。我如何检索下图中显示的数字,以便在字符串旁边(oeb ...)?谢谢。

enter image description here

我得到这个日志:enter image description here

+0

你是如何看到它的喃?你现在在你的函数中只显示一行代码,所以不可能看到真正发生的事情。 –

+0

console.log(ticketsBoughtByUser),然后我去firebase功能,我看到日志。这是整个功能。我只想得到“1”,或任何其他可能出现在那里的整数......当然,控制台日志是在让ticketBoughtByUser声明之后。 –

+0

对不起,NaN出现在我尝试这个时:Number(event.data.val();)。但是,我在我的问题中添加了以下日志。 –

回答

3

在你的情况,event.data.val()显然不会返回一个数字。它返回一个对象,你在日志中看到。如果您使用console.log(ticketsBoughtByUser)(不要使用字符串连接来构建消息),您实际上可以看到对象中的数据。

对于在数据库中显示的数据,我希望瓦尔要包含此数据(我不必键入它删节左右)对象:

{ 
    "oeb...IE2": 1 
} 

如果你想得到了1指出的对象,你必须使用字符串键,不管是字符串代表达成了进去:如果你想只是数量,而不是对象的位置您最初

const num = ticketsBoughtByUser["oeb...IE2"] 

给,你会n EED两个通配符它获得直接:

exports.lotteryTickets = functions.database 
     .ref('/lottery/ticketsneedstobeprocessed/{randomID}/{whatIsThis}') 
     .onWrite(event => { 
    const num = event.data.val() 
} 

我添加了一个通配符whatIsThis,这将匹配该字符串我上面节录。

但我真的不知道你的函数试图完成什么,所以这只是猜测你是否应该这样做。

+0

感谢它工作:) –

2

您还可以得到ticketsBoughtByUser值类似下面

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 

exports.sendNotification = functions.database.ref('/articles/{articleId}') 
     .onWrite(event => { 

     // Grab the current value of what was written to the Realtime Database. 
     var eventSnapshot = event.data; 

     //Here You can get value through key 
     var str = eventSnapshot.child("author").val(); 

     console.log(str); 

     }); 
相关问题