我正在使用此代码:

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

})


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

javascript - 从Cloud Functions for Firebase读取数据?-LMLPHP

我收到此日志:javascript - 从Cloud Functions for Firebase读取数据?-LMLPHP

最佳答案

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

对于您在数据库中显示的数据,我希望val是包含此数据的对象(已删除,因此我不必键入它):

{
    "oeb...IE2": 1
}


如果要从该对象中获取1,则必须使用字符串键来访问它,无论该字符串代表什么:

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


如果只需要数字而不是最初给定位置的对象,则将需要两个通配符直接获取它:

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


我为whatIsThis添加了通配符,该通配符将匹配我上面编辑的字符串。

但是我真的不知道您的功能要完成什么,因此只是在猜测您是否应该实际执行此操作。

07-24 16:52
查看更多