Send Push Notification from mongodb function using firebase

Hi,

I am trying to send push notification from mongodb function using firebase (fcm).

I have the following code working on node.js, which i am trying to replicate in function:
const admin = require(‘firebase-admin’);
let serviceAccount = require(’./serviceAccountKey.json’);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});

Uploaded all the relevant external dependencies.

Now, the problem is i don’t know how the following code will work:
let serviceAccount = require(’./serviceAccountKey.json’);

this line is looking for external json file (unfortunately, not able to upload it as dependencies)

Any help to make it work would be appreciated.

Thanks

3 Likes

hi,

If you set your Sender Id and API Key under Push Notifications -> Config you can use following function to send notifications:

exports = function(deviceToken){
  
  // Construct message
  const message = {
    "to": deviceToken,
    "notification": {
      "title": "Test Title",
      "body": "Test Message"
    }
  };
  
  // Send push notification
  const gcm = context.services.get('gcm');
  const result = gcm.send(message);
  console.log(JSON.stringify(result));
  return result;
};

regards

I suppose this answer is considered depricated now. What is the new way to deal with that? I am dealing with the same problems, that Firebase requires either a File or changing a environment variable in the shell. Both things are not an option as far as I know.

2 Likes

Hi Thomas, have you found the answer?

Yes, I solved the issue.

I created a secret in the MongoDB values and referenced it. Into the secret went the credentials itself (the JSON).

Then, you can read it from the functions like this (assuming you named the link ‘firebase_credentials’):

 const firebase_credentials = context.values.get("firebase_credentials");
 const doc = JSON.parse(firebase_credentials);
 admin.initializeApp({
     credential: admin.credential.cert(doc),
 });
2 Likes

May you please share what firebase-admin version you use? I assume you use it as Function dependency?

Many thanks,
Tomas

Hey.

I am using version 9.7.0

Hello developers,

I’m new in development, can someone fix my problem? I am facing an issue in connecting MongoDB with the firebase account.

Waiting for your reply!