Function triggered by a write operation on a collection in firebase

I’m using firebase database in my react app. I’m trying to write a function of firebase database that should be triggered automatically whenever a new document is inserted inside the collection “stories”. The function works in the following way:

  1. it collects the attributes of the newly inserted document ( which are titleIt,titleEn,descriptionIt and descriptionEn )
  2. it retrieves a certain document in the collection “stories_json”, which for now has an attribute json that is an array (empty for now)
  3. it pushes inside such array an object containing the attributes retrieved at point 1 ( which are titleIt,titleEn,descriptionIt and descriptionEn )
  4. it uploads the data on the document of the collection “stories_json”.

The goal is to obtain an array of objects.

The problem is that whenever i add a new document in the collection “stories”, the document inside the collection “stories_json” is not updated because the json array remains empty. Where is the mistake?

Here is the function I wrote.

exports.updateStoriesJson = functions.firestore
    .document("/stories/{storyId}")
    .onWrite(async (event) => {
      const storyData = event.after.data();
      if (storyData) {
        const titleIt = storyData.params.titleIt;
        const titleEn = storyData.params.titleEn;
        const descriptionIt = storyData.params.descriptionIt;
        const descriptionEn = storyData.params.descriptionEn;
        const json = {titleIt, titleEn, descriptionIt, descriptionEn};
        const jsdonDocCollection=admin.firestore().collection("stories_json");
        const jsonDoc=jsdonDocCollection.doc("7GaNrl34utwq7C9lvHz4");
        const docSnapshot = await firestore.get(jsonDoc);
        let jsonArray = docSnapshot.data().json;
        jsonArray.push(json);
        await jsonDoc.set({json: jsonArray});
      }
      return;
    });

Here is how the collection “stories_json look like”
enter image description here

  • 1

    i have a doubt, const docSnapshot = await firestore.get(jsonDoc); in this line you used firestore.get() but in this line const jsdonDocCollection=admin.firestore().collection("stories_json"); you used admin.firestore(). should it be admin.firestore().get(jsonDoc) ?

    – 




  • Sounds like an answer, @Jabir! 👍🎉😀

    – 

Leave a Comment