Mathias
Mathias

Reputation: 566

How to read a value from Firebase realtime database with a Google cloud functions?

I'm starting to use firebase cloud functions, and I have trouble reading an entry "Hello" from my database tree :

enter image description here

I'm trying to read the "Hello" value inside HANDLE/suj1/part1 from my tree. I am using a firebase cloud function that is triggered when I create an other entry with an IOS Application in the database inside "INTENT". The functions gets called well but every time I try to read the "Hello" value , it returns a null value in my firebase console where I expect it to return "Hello".

Here is the code I use :

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

exports.match = functions.database.ref('INTENT/{userid}').onCreate(snapshot => {

const user = snapshot.key


return admin.database().ref('HANDLE/suj1/part1').once('value', (snap) => {
    const hello = snap.val()
    console.log(hello) // Null
 });

Can someone tell what am I doing wrong ?

Upvotes: 0

Views: 1620

Answers (3)

Mathias
Mathias

Reputation: 566

I found out with this line and Frank's help:

admin.database().ref().once('value', (snap) => { console.log(JSON.stringify(snap.val())); });

That I had added a whitespace at the end of "HANDLE " in my path, which does not appear in the Firebase console. I had to delete the branch and create an other one.

Upvotes: 2

Gastón Saillén
Gastón Saillén

Reputation: 13179

please try this

const userName = admin.database().ref('/HANDLE/suj1/part1').once('value',function(snapshot) {

const hello = snapshot.val();
console.log(hello);

});

Upvotes: 1

Christophe Chenel
Christophe Chenel

Reputation: 1921

Try this:

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

exports.match = 
functions.database.ref('OTHERLOCATION/{userid}').onCreate((snapshot) => {
const user = snapshot.key

return admin.database().ref().child('HANDLE/suj1').once('value', function(snap) => {
const hello = snap.val().part1
console.log(hello) // "Hello"
});

Upvotes: 1

Related Questions