Reputation: 43
I am trying to get the value from author, but it says that it's undefined.
How do I get the value from a specific child from firebase in javascript in Cloud Functions for Firebase, the follwing code should work(?):
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushForHelp =
functions.database.ref('/schools/Vittra/alarms/active/{id}').onCreate(event => {
const id = event.params.id;
var eventSnapshot = event.data.val();
var ref = admin.database().ref("/schools/Vittra/alarms/{eventSnapshot}/authorId");
ref.once('value').then(function(snapshot) {
var author = snapshot.val();
});
const payLoad = {
notification: {
title: String(eventSnapshot),
body: String(author),
badge: '1',
sound: 'Intruder.mp3'
}
};
return admin.database().ref('fcmToken').once('value').then(allToken => {
if (allToken.val()) {
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payLoad).then(response =>
{
});
};
});
});
Upvotes: 0
Views: 3657
Reputation: 317677
You're ignoring the promise returned from this query:
ref.once('value').then(function(snapshot) {
var author = snapshot.val();
});
Before you can use the value of author
, you need to but the code that depends on author
inside the function that responds to that promise, more like this:
var author;
return ref.once('value').then(function(snapshot) {
author = snapshot.val();
return admin.database().ref('fcmToken').once('value')
}).then(function(snapshot) {
if (allToken.val()) {
const token = Object.keys(allToken.val());
const payLoad = ...
return admin.messaging().sendToDevice(token, payLoad)
}
}).then(function(response) {
// ...continue
})
The bottom line is that you need to learn how to chain your promises correctly.
Upvotes: 1
Reputation: 601
You have declared author inside the firebase callback.
var eventSnapshot = event.data.val();
var ref = admin.database().ref("/schools/Vittra/alarms/{eventSnapshot}/authorId");
ref.once('value').then(function(snapshot) {
var author = snapshot.val(); // Here is the problem
});
And you are using it here as :
const payLoad = {
notification: {
title: String(eventSnapshot),
body: String(author), // <------
badge: '1',
sound: 'Intruder.mp3'
}
};
define author outside like eventSnapshot , then you can use it further.
Use:
var eventSnapshot = event.data.val();
var author = '';
var ref = admin.database().ref("/schools/Vittra/alarms/{eventSnapshot}/authorId");
ref.once('value').then(function(snapshot) {
author = snapshot.val();
});
Upvotes: 0