0
votes

I am new to firebase cloud functions. So, I followed the tutorial in firebase youtube channel. So, I created a function that should trigger when firestore document added,but it didn't trigger.

this is the function

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

exports.whenAddData = functions.firestore
  .document("chats/{userId}")
  .onCreate((change, context) => {
    const msg = change.data().msg;
    const modifiedMsg = addImoji(msg);
    console.log("data changing");
    return change.ref({ msg: modifiedMsg });
  });

const addImoji = (msg) => {
  return msg.replace(/\bPizza\b/g, " ???? ");
};

firebase-functions version: "^3.6.1"

firestore db screenshot enter image description here

1
add a screenshot of ur databasePeter Haddad
screenshot addedS.Sachith
are you not getting console.log("data changing"); ?Peter Haddad
yha i am not getting console logS.Sachith
also cheked functions logS.Sachith

1 Answers

2
votes

First of all, your regex is wrong. It's case sensitive, which means the message from your screenshot "i love pizza" doesn't match "Pizza". To make it case insensitive (and thus match "Pizza", "pizza", "piZZA" ...) add the i flag at the end:

const addImoji = (msg) => {
  return msg.replace(/\bpizza\b/gi, "🍕");
};

Secondly, your function returns a database reference. It doesn't actually store the new data by calling set() or update(). Your code should be:

return change.ref.update({ msg: modifiedMsg });

Any async Firebase function should return a promise (and update() returns a promise). If it doesn't, the function won't terminate correctly.

By returning the result of update, your function will keep running until the asynchronous work of writing the new msg to the database is completed.