![](/img/trans.png)
[英]How do I get to a specific node in Google Cloud Function from within a `onWrite` function triggered by another node event?
[英]Cloud Function - onWrite is not triggered when a new document is created
我有一個包含文檔列表的“用戶”集合,每個文檔都有一個用戶對象和一個子集合“通知”。 每當用戶收到新通知時,都會在其子集合 Notifications 下創建一個新文檔。
未觸發雲功能中的觸發器。
這是我的 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) => {...});
事實上,Cloud Functions for Firestore 是在文檔級別觸發的。 此處和此處的文檔中的更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.