Roggie
Roggie

Reputation: 1217

Getting empty snapshot when reading Firebase Database in Javascript?

I have the following database structure:

enter image description here

I am trying to get the list of values under registrationTokens to then execute an FCM notification to the list of tokens. But the output to the console is empty even though there is a token under the child node. Am I missing something here?

Console output:

registrationTokens [ '0' ]

Part of my JS function code below:

return admin.database().ref('/fcmtokens/' + toId + '/registrationTokens').once('value').then((userTok) => {

    const registrationTokens = Object.keys(userTok.val());

    console.log('registrationTokens', registrationTokens);
});

Upvotes: 1

Views: 719

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

Your console output is exactly as I'd expect. You've read the following children from the database:

0: 'c4P...'

Then you asked for the keys of that object to be printed, as returned by Object.keys(). Note that this key a key/value pair: the key is 0 and the value is 'c4P...'. This means that the following call:

Object.keys(userTok.val());

Is going to return an array of keys of the children. Since there is one child with a key of 0, you get this array:

[ '0' ]

So, I'd say your function is working exactly as you coded it. If you want the token values instead, try this:

If you want to tokens for each key instead, maybe you should use Object.values() instead:

Object.values(userTok.val());

I'd expect that to return an array of all the values associated with they keys.

Upvotes: 1

Related Questions