【问题标题】:Get Document in Firestore Cloud Function在 Firestore 云函数中获取文档
【发布时间】:2019-12-03 06:15:19
【问题描述】:

我正在创建一个 Firebase 云函数,该函数会在特定用户的评分更新时向其发送消息(来自 Firestore 的触发器)。

到目前为止我有;

// 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);
    })
})

我需要访问 {userID} 文档的 fcmToken 字段以使用下面如何通过使用通配符 {userID} 来处理此问题

【问题讨论】:

    标签: javascript google-cloud-firestore google-cloud-functions


    【解决方案1】:

    这在documentation 中用于通配符:

    exports.sendNewRatingNotification =
    functions.firestore.document('users/{userID}/ratings/{ratingID}').onWrite((change, context) => {
        const userID = context.params.userID
    })
    

    注意回调的第一个参数不是context,而是描述文档前后状态的Change对象。第二个参数是包含更改参数的上下文。

    【讨论】:

    • 谢谢,@Doug 我可以直接访问 fcmToken 字段(const fcmToken = context.param.fcmToken)还是我需要获取用户的文档数据然后访问 fcmToken 字段。
    • 上下文中没有令牌字段。您必须为每个用户存储和检索它。
    【解决方案2】:

    我已经按照上面接受的答案实施了这个过程。

    我的 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);
                });
            };
        });
    });
    

    【讨论】:

      【解决方案3】:

      如果您检查functions-samples/fcm-notifications 存储库的行号30-31

      你会得到使用:

        const userID= context.params.userID;
      

      希望对你有帮助。

      谢谢。

      【讨论】:

        猜你喜欢
        • 2018-03-28
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-23
        • 1970-01-01
        相关资源
        最近更新 更多