[英]Get Document in Firestore Cloud Function
I am creating a Firebase cloud function that messages a particular user when their rating has been updated (a trigger from Firestore).我正在创建一个 Firebase 云函数,它会在特定用户的评级更新(来自 Firestore 的触发器)时向其发送消息。
So far I have;到目前为止,我有;
// Send New Rating Notifications
exports.sendNewRatingNotification = functions.firestore.document('users/{userID}/ratings/{ratingID}').onWrite((context) => {
// Get {userID} and field of fcmToken and set as below
var fcmToken = fcmToken;
var payload = {
notification: {
title: "You have recieved a new rating",
body: "Your rating is now..."
}
}
return admin.messaging().sendToDevice(fcmToken, payload).then(function(response) {
console.log('Sent Message', response);
})
.catch(function(error) {
console.log("Error Message", error);
})
})
I need to access the {userID}
documents' fcmToken field to use below how to I approach this from using the wildcard {userID}
我需要访问
{userID}
文档的 fcmToken 字段以在下面使用如何使用通配符{userID}
This is spelled out in the documentation for wildcards:这在通配符的文档中有详细说明:
exports.sendNewRatingNotification =
functions.firestore.document('users/{userID}/ratings/{ratingID}').onWrite((change, context) => {
const userID = context.params.userID
})
Note that the first argument to the callback is not context
, it's Change object that describes the before and after state of the document.请注意,回调的第一个参数不是
context
,而是描述文档前后状态的 Change 对象。 The second argument is a context that contains the parameters of the change.第二个参数是包含更改参数的上下文。
I've implemented the process from the accepted answer above.我已经从上面接受的答案中实现了这个过程。
My Firebase Function is as follows;我的 Firebase 功能如下;
exports.sendNewRatingNotification = functions.firestore.document('users/{userID}/ratings/{ratingID}').onWrite((change, context) => {
var userRef = admin.firestore().collection('users').doc(context.params.userID);
return userRef.get().then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
const data = change.after.data();
const fcmToken = doc.data().fcmToken;
var payload = {
notification: {
title: "New Rating",
body: "You have recieved a " + data["rating"] + "* rating"
}
}
return admin.messaging().sendToDevice(fcmToken, payload).then(function(response) {
console.log('Sent Message:', response);
})
.catch(function (error) {
console.log('Error Message:', error);
});
};
});
});
If you check line number 30-31 of functions-samples/fcm-notifications repository.如果您检查functions-samples/fcm-notifications存储库的第30-31行。
You will get using:您将开始使用:
const userID= context.params.userID;
Hope it will helps you.希望它会帮助你。
Thank you.谢谢你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.