javascript - 云函数 - 创建新文档时不会触发 onWrite
问题描述
我有一个“用户”集合,其中包含一个文档列表,每个文档都有一个用户对象和一个子集合“通知”。每当用户收到新通知时,都会在其子集合通知下创建一个新文档。
云函数中的触发器未触发。
这是我的 Firestore 结构:
这是我的功能:
let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.collection('Users/{userID}/Notifications/{notificationId}')//
.onWrite(async (change,context) => {
// get receiver ID
const receiverId = context.params.userID;
// get notification object
const notificationObject = change.after.val();
// get sender ID
const senderUid = notificationObject.senderId;
console.log('sending notification to: ' + senderUid);
if (senderUid === receiverId) {
// this should never be called
console.log('sender is the receiver.');
}
// receiver's token
const getTokenPromise = await admin.firestore().collection('Users').doc(receiverId).once('value');
const token = getTokenPromise.val().deviceToken;
// sender user object
const sender = await admin.firestore().collection('Users').doc(senderUid).once('value');
const payload = {
data: {
senderName: sender.val().userName,
senderPhoto: sender.val().userPhoto,
object: JSON.stringify(notificationObject)
}
};
try {
const response = await admin.messaging().sendToDevice(token, payload);
console.log("Successfully sent notification:", response);
}
catch (error) {
console.log("Error sending notification:", error);
}
});
我做错了什么?
解决方案
你应该声明你的函数
exports.sendNotification = functions.firestore.document('Users/{userID}/Notifications/{notificationId}')//
.onWrite(async (change,context) => {...});
而不是
exports.sendNotification = functions.firestore.collection('Users/{userID}/Notifications/{notificationId}')//
.onWrite(async (change,context) => {...});
事实上,Firestore 的 Cloud Functions 是在文档级别触发的。更多细节here和here in the doc。
推荐阅读
- html - 如何在 Bootstrap 的列顶部对齐文本?
- google-chrome - Chromium 不会从影子 DOM 内容中推断菜单项名称
- c# - 使用包含条件的 Lambda 表达式在 C# 中创建属性
- java - Java等价于python装饰器
- r - ggplot_line:用 X 轴值标记前 2 个峰值
- firebase - Firebase Cloud Function:& Flutter:无法在模拟器上使用 https 可调用函数 [firebase_functions/unavailable] UNAVAILABLE
- database - 如何处理 MongoDB 中的库存/库存数据?
- python - 从数据框列中提取 TLD 和 SLD 到新列中
- java - 使用 Java SDK 在 Avilability Zone 中部署 Azure VM 不起作用
- python - RuntimeError:事件循环已关闭(对于不和谐的 Py 机器人)