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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-09-12 11:00:00 +0000
Seen: 9 times
Last updated: Jan 18 '22
How can a whole collection be removed using Cloud Functions?
Can the time zone be configured to Europe/Berlin in Google Cloud Scheduler?
As a beginner in data analysis, how can I connect my cloud editor to cloud Dataproc for Hadoop?
How can I utilize the official SDK to acquire a file from Huawei cloud?
What is the process of uploading files to OSS cloud service using Flutter?
How can several occurrences of Spring Cloud Kafka Binder be utilized to write to a common file?
Can Salesforce Health Cloud and Salesforce Marketing Cloud be integrated with each other?
What is the method to distinguish between user and organization tokens in Terraform cloud?