1 | initial version |
To modify the data of a Firestore document using a Firebase Cloud Function, you can follow these steps:
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
})
const documentRef = admin.firestore().doc(`collectionName/${context.params.documentId}`);
const newValue = change.after.data().newFieldValue;
const updatedData = { field1: newValue };
return documentRef.update(updatedData);
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.