K. Rhoda
K. Rhoda

Reputation: 191

How to get a value from Firebase Database and assign it to a value in Firebase Cloud Functions?

So I'm using firebase as a backend to a demo app, and I like the stack quite a bit, but I'm hung up on one issue, I can't figure out how to retrieve values from the database (I've got keys just fine).
Simply put, I'm sending information from one device that contains the "friendly-name" of another device it is trying to reach to a firebase function. The function code looks like this:

exports.connectMe = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
    admin.database().ref('calls/' + req.body.id + '/').set({
        target: req.body.target,
        caller: req.body.caller,
        time: req.body.time
    });

    const target = req.body.target;
    console.log(`target: ${target}`);
    const targetCall = admin.database().ref(`tokens/${target}/token`);
    console.log(targetCall);
    // const targetValue = targetCall.val();
    res.status(200).send("Thanks For The Call!");
    });    
});

The variable, targetCall is correctly pointed at the db entry that I want to reach, but I cannot extract the value for the life of me. The token located at admin.database.ref is required to be placed in a http request. How do I get the value? The commented out code shows the variable I would want to store it in, but I know that .val() is not a method of reference.
For the record, admin is set to require('firebase-admin'); earlier in the code.

Upvotes: 1

Views: 2010

Answers (2)

sketchthat
sketchthat

Reputation: 2688

You are very close to getting the database query to work.

Take a look at the Firebase Documentation. It explains how to access the structured data.

exports.connectMe = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        const callRef = admin.database().ref('calls/' + req.body.id + '/').set({
            target: req.body.target,
            caller: req.body.caller,
            time: req.body.time
        });

        const target = req.body.target;
        console.log(`target: ${target}`);

        const takenRef = admin.database().ref(`tokens/${target}/token`)
            .once('value');

        Promise.all([callRef, takenRef])
            .then(results => {
                const snapshot = results[1]; // Promise of `takenRef`
                console.log(snapshot.val()); // This is the data from the database...

                res.status(200).send("Thanks For The Call!");
            });
    });    
});

See the updated code, I've added .once('value').then(snapshot onto your query which gives you access to the data.

Upvotes: 2

Jen Person
Jen Person

Reputation: 7546

You need to call the function once(), as found in the documentation:

targetCall.once("value", function(data) {
  const targetValue = data.val();
  res.status(200).send("Thanks For The Call!");
});

Upvotes: 2

Related Questions