0

I have this code below which works (no syntax or any other errors) except that the output of this code displays all the results under /server/name:

i.e:

We have a new event: { des: 'test123', name: 'Test', nice: 'wew' } lol 

Here is the Code in functions/index.js:

exports.sendFollowerNotification = functions.database.ref('/server/name').onWrite(event => { admin.database().ref("/server/name").limitToLast(1).on('child_added', function(snapshot) { console.log('We have a new event:', snapshot.val()); }); 

Here is the DB:

enter image description here

Update 2:

 exports.sendFollowerNotification = functions.database.ref('/server/name/{num}').onWrite(event => { console.log('We have a new event:', event.data.val(), 'lol'); }); 

Output in Logs:

Update 3:

enter image description here

And

enter image description here

6
  • What is the function's expected behavior? What are you trying to achieve? Commented Jun 23, 2017 at 0:20
  • @JenPerson Send FCM (firbease cloud messaging) of new events added to DB Commented Jun 23, 2017 at 1:19
  • Ah I see. I'm trying to understand the purpose of the listener inside the function. Why not use event.data.val() to get the data of the new event? Commented Jun 23, 2017 at 1:22
  • @JenPerson event.data.val() returns all data too. I don't know how to modify functions.database.ref('/server/name').onWrite to return new elements only Commented Jun 23, 2017 at 1:25
  • ok so you don't want to return the value of "1", but the value of one of those test strings? Like just "Test" or "cool"? If so, I have the solution Commented Jun 23, 2017 at 1:28

1 Answer 1

2

Currently, the trigger is attached higher in the path than you want.

Instead,if you're planning on having multiple lists of events to listen to and this is just list 1 of many, use a wildcard:

exports.sendFollowerNotification = functions.database.ref('/server/name/{num}/{notification}').onWrite(event => { ... }) 

You can choose wildcard names that better fit your specific code.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for the help Jen, However, according to logs events.data still outputs all values. I updated my question with a picture
it does work, but because you are labeling your keys '1, 2, 3...' Firebase interprets this as an array and therefore shows an array. If you use different keys, it works. I tried it myself just now.
that's weird, can you post the whole code ? Maybe because I'm not returning a promise or something ? Here is the log after modifiying the DB i.imgur.com/u5K2UM1.png & i.imgur.com/9G8URDE.png
@Suhaib update your question to reflect what your code looks like now.
Alright, I've updated my answer and I tested it to make sure it works as expected. I realize I had to go even deeper into the path.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.