简体   繁体   English

从Cloud Functions for Firebase读取数据?

[英]Read data from Cloud Functions for Firebase?

I am using this code: 我正在使用此代码:

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

})

But ticketsBoughtByUser is not correct. 但是ticketsBoughtByUser是不正确的。 How can I retrieve the the number shown in the picture below, so next to the string (oeb...)? 我如何检索下图中显示的数字,因此在字符串(oeb ...)旁边? Thank you. 谢谢。

在此处输入图片说明

I get this log: 我得到此日志: 在此处输入图片说明

In your case, event.data.val() obviously doesn't return a number. 在您的情况下, event.data.val()显然不会返回数字。 It returns an object, which you are seeing in the log. 它返回一个对象,您将在日志中看到该对象。 You can actually see the data in the object if you console.log(ticketsBoughtByUser) (don't use string concatenation to build the message). 如果您使用console.log(ticketsBoughtByUser)则实际上可以在对象中看到数据(不要使用字符串串联来构建消息)。

For the data you show in the database, I would expect the val to be an object that contains this data (redacted so I won't have to type it): 对于您在数据库中显示的数据,我希望val是包含此数据的对象(已删除,因此我不必键入它):

{
    "oeb...IE2": 1
}

If you want to get the 1 out of that object, you'd have to reach into it using the string key, whatever that string represents: 如果要从该对象中取出1 ,则无论该字符串代表什么,都必须使用字符串键到达该对象:

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

If you want just the number and not the object at the location you originally gave, you will need two wildcards to get at it directly: 如果需要数字而不是最初给定位置的对象,则将需要两个通配符直接获取它:

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

I added a wildcard for whatIsThis , which will match that string I redacted above. 我为whatIsThis添加了一个通配符,它​​将与我在上面编辑的那个字符串匹配。

But I don't really know what your function is trying to accomplish, so it's just speculation as to whether or not you should actually do that. 但是我真的不知道您的功能要完成什么,因此只是在猜测您是否应该实际执行此操作。

You can also get the ticketsBoughtByUser value like below 您还可以像下面那样获取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);

        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM