我根本看不到我要去哪里。我的Cloud Firestore位于“ europe-west3”上,功能已部署到“ europe-west1”上(文档告诉我,这是距离west3最近的位置)。
结构是这样的:我有一堆“票”,每个“票”都可以有一个名为“ comments”的子集合。因此,控制台如下所示:
上传成功:
该功能代码取自官方代码示例 Github repo for Function samples
这是我的代码的样子:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.countComments = functions.region('europe-west1').database.ref('/tickets/{ticketId}/comments/{commentsid}')
.onWrite(
async (change) => {
const ticketsRef = change.after.ref.parent;
const countRef = ticketsRef.parent.child('comments_count');
let increment;
if(change.after.exists() && !change.before.exists()) {
increment = 1;
} else if(!change.after.exists() && change.before.exists()) {
increment = -1;
} else {
return null;
}
await countRef.transaction((current) => {
return (current || 0) + increment;
});
console.log('Counter updated');
return null;
});
exports.recountComments = functions.region('europe-west1').database.ref('/tickets/{ticketId}/comments_count')
.onDelete(
async (snap) => {
const counterRef = snap.ref;
const collectionRef = counterRef.parent.child('comments');
const commentsData = await collectionRef.once('value');
return await counterRef.set(commentsData.numChildren());
}
)
现在,问题在于这些功能根本无法启动。无论是通过客户端(Flutter应用程序)推送更改,还是直接在Firebase控制台中更改内容,我都不会在日志中看到任何内容。
在绝望中,我还试图简单地听“ / tickets”,因为该路径下的任何更改也应触发-但没有任何作用。
所以。我忽略了哪些显而易见的事情?而且,是的,我查看了其他问题/答案,但是什么都没想到...
编辑:
这是经过纠正的版本,可能不是最佳版本。
exports.countComments = functions.region('europe-west1').firestore.document('/tickets/{ticketId}/comments/{commentsId}')
.onWrite(
async (change, context) => {
const ticketId = context.params.ticketId;
const ticketRef = admin.firestore().collection('tickets').doc(ticketId);
let increment;
if(change.after.exists && !change.before.exists) {
increment = 1;
} else if(!change.after.exists && change.before.exists) {
increment = -1;
} else {
return null;
}
return transaction = admin.firestore().runTransaction(t => {
return t.get(ticketRef)
.then(doc => {
let count = (doc.data().comments_count || 0) + increment;
t.update(ticketRef, {comments_count: count});
});
}).then(res => {
console.log('Counter updated');
}).catch(err => {
console.log('Transaction error:', err);
});
});
答案 0 :(得分:1)
您的数据库是Cloud Firestore,但是您已经编写了一个实时数据库触发器。他们是两个完全不同的数据库。请改为遵循writing Cloud Firestore triggers的文档。
您的功能将像这样启动:
functions.region('europe-west1').firestore.document('...')
请注意“ firestore”而不是“数据库”。