Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To modify the data of a Firestore document using a Firebase Cloud Function, you can follow these steps:

  1. Define the Cloud Function: First, you need to define the Cloud Function that will modify the data. You can define it in the index.js file of your functions folder. For example:
const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();
// Define the Cloud Function
exports.modifyDocument = functions.firestore.document('collectionName/{documentId}').onUpdate((change, context) => {
    // code to modify data
})
  1. Get the Document Reference: Use the context object to get the reference to the Firestore document that needs to be modified. For example:
const documentRef = admin.firestore().doc(`collectionName/${context.params.documentId}`);
  1. Modify the Data: Update the values of the fields of the document by using the set() method to set the values of the fields you want to modify. For example:
const newValue = change.after.data().newFieldValue;
const updatedData = { field1: newValue };
return documentRef.update(updatedData);
  1. Return a Promise: Return a promise that resolves when the data is successfully modified. For example:
return documentRef.update(updatedData).then(() => {
    console.log('Document Updated Successfully');
    return null;
}).catch(error => {
    console.log('Error Upating Document: ', error);
    return null;
});

The final Cloud Function would look something like this:

exports.modifyDocument = functions.firestore.document('collectionName/{documentId}').onUpdate((change, context) => {

    const documentRef = admin.firestore().doc(`collectionName/${context.params.documentId}`);

    const newValue = change.after.data().newFieldValue;
    const updatedData = { field1: newValue };

    return documentRef.update(updatedData).then(() => {
        console.log('Document Updated Successfully');
        return null;
    }).catch(error => {
        console.log('Error Upating Document: ', error);
        return null;
    });

});

This Cloud Function will modify the value of the field1 to the newFieldValue whenever there is an update made to the document in the collectionName collection.