以下是一个函数,它可以检查子文档是否更新并返回父文档中所有值的总和,并将其作为 Cloud Function 部署到 Firebase 云:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.calculateSum = functions.firestore.document('parentCollection/{parentId}/childCollection/{childId}').onWrite((change, context) => {
const parentId = context.params.parentId;
const childId = context.params.childId;
const parentRef = admin.firestore().collection('parentCollection').doc(parentId);
const childRef = parentRef.collection('childCollection').doc(childId);
return childRef.get().then((childDoc) => {
if (childDoc.exists) {
console.log('Child document with ID', childId, 'has been updated');
return parentRef.collection('childCollection')
.get()
.then((snapshot) => {
let sum = 0;
snapshot.forEach((doc) => {
const data = doc.data();
if (data.value !== undefined) {
sum += data.value;
}
});
console.log('Calculated sum:', sum);
return parentRef.update({
sumOfValues: sum
});
})
} else {
console.log('Child document with ID', childId, 'does not exist');
return null;
}
}).catch((error) => {
console.error('Error getting child document:', error);
return null;
});
});
此函数监视了“parentCollection/{parentId}/childCollection/{childId}”路径下的所有写入事件。如果子文档被更新,则该函数会获取 parentCollection 集合中的所有文档,并返回所有文档中值的总和。然后,它会将总和保存在父文档中的 sumOfValues 字段中。