Dayakargoud Bandari
Dayakargoud Bandari

Reputation: 108

Undefined field when sending notification to users using firebase cloud functions

I am trying to send notifications to user those who subscribed to a topic.. The notifications are working fine but notification title shows 'undefined' and there is no image as well.

This is my code.

const functions = require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotifications = functions.database.ref('All_Events/{pushId}')
  .onWrite(event => {
     const mydata=event.after.val();

     var topic='updates';

     var message={
       data:{
           title: String(mydata.title),
           content: String(mydata.desc),
           url: String(mydata.image)
       },
       topic:topic
     };
     console.log('posted succesfully');
     console.log('title = ',mydata.title);
     return admin.messaging().send(message)
});

My Database Layout: my database layout

How do I get a reference to CSE, ECE, etc. from the database?

Upvotes: 1

Views: 176

Answers (1)

robsiemb
robsiemb

Reputation: 6374

I suspect the problem is that your trigger is set to match: "All_Events/*", with context.params.pushId matching the 'CSE', 'ECE', etc strings from your database (That's the answer to your second question).

The answer as to why the objects (title, image) are showing as undefined is explained in this documentation.

Notably:

In either case, Firebase interprets that the event occurs at /foo/bar, and the event data includes the old and new data at /foo/bar.

That is, the object that is being passed to your function is, for example, the All_Events/CSE tree in its entirety (and it could be quite large!). At the top level, there don't appear to be any 'title' or 'image' fields, so those will be undefined when your function runs.

You probably want to be matching on All_Events/{category}/{pushId} instead.

Then, your 'CSE' or 'ECE' items will be in context.params.category, and the object that I assume has the fields you're looking for (the image doesn't show them anywhere so I assume they are in the objects with the hash identifiers) will be the one that is actually passed to your function, with the hashed identifier in context.params.pushId.

You should also be aware that onWrite will also fire for deletes, so you should probably at least check to see that event.after still exists when this function runs. See more about reading the previous/next value.

Upvotes: 1

Related Questions