Firebase 函数介绍如何从 Firebase 数据库中获取值数组



我想在我使用的第二个函数中获取数据库所有用户的数组 "返回admin.database((.ref("/Usuarios"(.once('value'( ",以便我们可以向所有这些用户发送通知。如何所有用户都进入第二个功能?谢谢

我有这个代码:

let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotificationNewAd = functions.database.ref('/Alertas/{notiId}').onWrite((change, context) => {
// Only edit data when it is first created.
if (change.before.exists()) {
return null;
}
// Exit when the 
data is deleted.
if (!change.after.exists()) {
return null;
}

//te escribe el json de el mensaje nuevo
const afterData = change.after.val();
console.log("afterData: ", afterData);
//get lat and lng of Ad
const name = afterData.name;
console.log("Name: "+name);
//get lat and lng of Ad
const lat = afterData.lat;
const lng = afterData.lng;
console.log("Lat y Lng", "lat: "+lat+" lng: "+lng);
//get lat and lng of Ad
const adType = afterData.typeAd;
console.log("Tipo: "+adType);
//get the user id of the ad
const notiId = context.params.notiId;
console.log("notiId: ", notiId);
const userId = afterData.userId;
console.log("userId: ", userId);
return admin.database().ref("/Usuarios").once('value')
.then(snap => {
const userName = snap.child("name").val();
return console.log("userName: ", userName);
});
});

看起来这就是你要问的:

exports.sendNotificationNewAd =
functions.database.ref('/Alertas/{notiId}')
.onCreate((noti_snap, context) => {
//te escribe el json de el mensaje nuevo
const notif = noti_snap.val();
console.log("notif: ", notif);
//get lat and lng of Ad
const name = notif.name;
console.log("Name: " + name);
//get lat and lng of Ad
const lat = notif.lat;
const lng = notif.lng;
console.log("Lat y Lng", "lat: " + lat + " lng: " + lng);
//get lat and lng of Ad
const adType = notif.typeAd;
console.log("Tipo: " + adType);
//get the user id of the ad
const notiId = context.params.notiId;
console.log("notiId: ", notiId);
const userId = notif.userId;
console.log("userId: ", userId);
return admin.database().ref("/Usuarios").once('value')
.then(snap => {
let children = [];
snap.forEach(child_snap => {
children.push(child_snap.val()); // build children
});
return children;
})
.then(children => {
children.map(child => {
let message = {
notification: {
title: "message",
body: "body"
},
token: child.device_token
}
admin.messaging().send(message).catch(console.log);
});
return null;
})
.then( () => { 
return notif.ref.remove(); // consume send request
})
.catch(console.log);
});

相关内容

  • 没有找到相关文章

最新更新