SHUBHAM SHEDGE
SHUBHAM SHEDGE

Reputation: 1913

Send Notification when Document is Created using Cloud Function

I'm using Firebase and Firestore as database

I want to push a new notification when a document is created at the user notification collection.

It should be something like this,

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

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

exports.sendNotificationToTopic = functions.firestore.document('notification/{notificationId}').onWrite(async  (event) => {

  var message ={
      notification: {
          title: "This is Title",
          body: "This is the Body",
          user: "fA0eLup_TUKVzdBkQbd3Qb:APA91bHuSuZOjdJgXn6xBndhQQkfnzm1pdLl9x3B2FZUYcYQULVPJFRbERezPuLoXD4QCUU2yalLUvgRfEas4B0sKAcwOkcmGkudLFvQWqTT7uhG21pKffTNTz5GvWKcD2-hKkfPq9Gq"

      },

      "token": user


  };

  let response=await admin.messaging().send(message);
  console.log(response);

});

Yes I'm using Cloud Function

And when I create a document in notification collection I didn't get notification this is my DB structure

And I got some error in Cloud function log

sendNotificationToTopic 
Error: Exactly one of topic, token or condition is required at FirebaseMessagingError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:42:28) at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:88:28) at new FirebaseMessagingError (/srv/node_modules/firebase-admin/lib/utils/error.js:254:16) at Object.validateMessage (/srv/node_modules/firebase-admin/lib/messaging/messaging-types.js:46:15) at Messaging.send (/srv/node_modules/firebase-admin/lib/messaging/messaging.js:207:27) at exports.sendNotificationToTopic.functions.firestore.document.onWrite (/srv/index.js:22:40) at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23) at /worker/worker.js:825:24 at <anonymous> at process._tickDomainCallback (internal/process/next_tick.js:229:7) 

Upvotes: 2

Views: 2061

Answers (1)

Sanjan Hegde
Sanjan Hegde

Reputation: 83

Add a token to your var message variable.

{ "notification": { title: "This is Title", body: "This is the Body", }, "token": user_info.device_id } You can get the token from Tools --> Firebase --> Cloud Messaging --> Step 4 Firebase cloud messaging step 4 implementation explains it briefly.

enter image description here

Upvotes: 1

Related Questions