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:
- it collects the attributes of the newly inserted document ( which are titleIt,titleEn,descriptionIt and descriptionEn )
- it retrieves a certain document in the collection “stories_json”, which for now has an attribute json that is an array (empty for now)
- it pushes inside such array an object containing the attributes retrieved at point 1 ( which are titleIt,titleEn,descriptionIt and descriptionEn )
- 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”
i have a doubt,
const docSnapshot = await firestore.get(jsonDoc);
in this line you usedfirestore.get()
but in this lineconst jsdonDocCollection=admin.firestore().collection("stories_json");
you usedadmin.firestore()
. should it beadmin.firestore().get(jsonDoc)
?Sounds like an answer, @Jabir! 👍🎉😀