Naadril
Naadril

Reputation: 21

How to add child to a List in Firebase Realtime Database with a cloud function?

I try to create a Firebase cloud function that react on new "Event" in the realtime database and add a "notification" object in a notification list for the corresponding users. i succeed to get new event information,to push a notification a corresponding users but not in a list format (but in hashmap format).

So I tried to get the numbers of children in order to push new notification with the good index. I don't know how to manage promises in that case.

The idea is to get sport_name and level from the new event, to get corresponding users in Sport and add notification for each users.

Table

Upvotes: 2

Views: 823

Answers (1)

Naadril
Naadril

Reputation: 21

This code works but it create a random key for notifications. How to put integer (0,1,2,...) as key in order to have a list in my database ?

<pre>
exports.detectEvent = functions.database
.ref("Event/{eventID}")
.onCreate((snapshot, context) => {
    const event = snapshot.val();
    const sport = event.sport.name;
    const level = event.niveau;
    const name = event.name;
    var promises=[];
    var path = "Sports/" + sport + "/" + level;
    var notif = {
        type : "Event",
        contentID : context.params.eventID,
        message : sport + " : Un nouvel événement vous correspond ! ",
        seen : false,
        date : "01"
    };
    console.log('path ', path);
    return admin.database().ref(path).once("value", function(result) {
        var datas = result.val();
        for (var property in datas)  {
            if (datas.hasOwnProperty(property)) {
                promises.push(admin.database().ref("Users/"+datas[property]+"/notifications").push(notif));
            }

        }
        return Promise.all(promises);
    })
});

<code>

Upvotes: 0

Related Questions