如何在Firestore触发器中读取文档属性

时间:2019-09-06 04:57:46

标签: android firebase google-cloud-firestore firebase-cloud-messaging google-cloud-functions

我正在尝试使用Firebase云消息传递向Android应用程序的用户发送通知。我正在使用云Firestore触发器,但是当尝试访问用户节点的属性时,它们是未定义的。

这是我的index.js:


const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.notifyNewMessage = functions.firestore
    .document('conversations/{conversation}/messages/{message}')
    .onCreate((docSnapshot, context) => {
      const message = docSnapshot.data();
      const recipientId = message['recipientId'];
      const senderName = message['senderName'];

      return admin.firestore().collection("users").doc(recipientId).get().then(userDoc => {

        const registrationTokens = userDoc.registrationTokens;
        console.log("registrationTokens  = "+ registrationTokens);

        const notificationBody = message['message'];
        const payload = {
          notification : {
            title : senderName + " sent you a message,",
            body: notificationBody,
            clickAction: "ConversationActivity"
          },
          data : {
            contactName : senderName,
            userId : message['senderId']
          }
        }

        return admin.messaging().sendToDevice(registrationTokens, payload).then(response => {
          const stillRegisteredTokens = registrationTokens;

          response.results.forEach((result, index) => {
            const error = result.error;
            if (error){
              const failedRegistrationToken = stillRegisteredTokens['index'];
              if (error.code === 'messaging/invalid-registration-token'
                  || error.code === 'messaging/registration-token-not-registered') {
                      const failedIndex = stillRegisteredTokens.indexOf(failedRegistrationToken)
                      if (failedIndex > -1) {
                          stillRegisteredTokens.splice(failedIndex, 1);
                      }
                  }
            }
          })
          return admin.firestore().doc("users/" + recipientId).update({
              registrationTokens: stillRegisteredTokens
          })
        })
      })
    })

因此,我收到一个错误消息“ sendDevice()参数必须是非空数组或非空字符串”

更新

registrationToken是未定义的,因为我叫userDoc而不是userDoc.data()

现在registrationTokens不为null也不为空,但我仍然收到错误消息:

Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array.

0 个答案:

没有答案