我试图从作者那里获得价值,但它说这是未定义的。
如何从Firebase的Cloud Functions中的javascript中获取firebase中特定子项的值,以下代码应该有效(?):
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 =>
{
});
};
});
});
答案 0 :(得分:1)
您忽略了此查询返回的承诺:
ref.once('value').then(function(snapshot) {
var author = snapshot.val();
});
在使用author
的值之前,您需要的是依赖于author
里面的代码响应该承诺的函数,更像是这样:
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
})
最重要的是,你需要学习如何正确地链接你的承诺。
答案 1 :(得分:0)
您已在firebase回调中声明作者。
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
});
你在这里使用它:
const payLoad = {
notification: {
title: String(eventSnapshot),
body: String(author), // <------
badge: '1',
sound: 'Intruder.mp3'
}
};
在eventSnapshot之外定义作者,然后你可以进一步使用它。
使用:
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();
});