Elhoej
Elhoej

Reputation: 751

Can't access Datasnapshot value with Cloud Functions

I'm trying to use cloud functions to check periodically if a meeting deadline has passed. But I can't figure out how to access the value of the snapshot that I get returned. Here is my code:

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


exports.checkForMeetings = functions.https.onRequest((req, res) => 
{
    var query = admin.database().ref("meetings").orderByChild("deadline");
    query.once("value").then((snapshot) => 
    {
        var currentDate = new Date();
        var currentTime = currentDate.getTime();
        var seconds = (currentTime / 1000).toFixed(0);
        var deletion = {};
        var updates = {};

        console.log(seconds);

        snapshot.forEach((child) =>
        {
            console.log(child.value)
            if (seconds > child.value)
            {
                //Rest of the code here
            }
        }
    }
}

The meeting database node looks like this

database example

Right now the console just prints 'undefined' when I try to print the deadline value, and the if statement doesn't execute. What's the solution to this?

Upvotes: 1

Views: 604

Answers (1)

Grimthorr
Grimthorr

Reputation: 6926

The Query#once() method callback returns a DataSnapshot, likewise so does the DataSnapshot#forEach() iterator, so you'll need to use the val() method to obtain the value:

val

val() returns any type

Extracts a JavaScript value from a DataSnapshot.

Returns

any type The DataSnapshot's contents as a JavaScript value (Object, Array, string, number, boolean, or null).

For example:

snapshot.forEach((child) =>
{
    console.log(child.val())
    if (seconds > child.val())
    {
        //Rest of the code here
    }
}

Upvotes: 4

Related Questions