【问题标题】:Firebase.child failed: First argument was an invalid pathFirebase.child 失败:第一个参数是无效路径
【发布时间】:2017-12-01 00:10:58
【问题描述】:

可能重复。不确定。

connections: {
      connectionID : {
         userID: true,
         anotherUserID: true
      },

 users: {
   userID : {
       deviceToken : "tokenID",
       name : "Display Name"
   },
   anotherUserID : {
       deviceToken : "tokenID",
       name : "Display Name"
   }
 }

等等等等。

这是我的 index.js:

exports.sendConnectionNotification = functions.database.ref('/connections/{connectionID}/{userID}').onWrite(event => {

  const parentRef = event.data.ref.parent;
  const userID = event.params.userID;
  const connectionID = event.params.connectionID;

   // If un-follow we exit the function.
  if (!event.data.val()) {
    return console.log('Connection', connectionID, 'was removed.');
  }

  // Get the list of device notification tokens.
  const getDeviceTokensPromise = admin.database().ref('/users/${userID}/deviceToken').once('value');

  // Get the user profile.
  const getUserProfilePromise = admin.auth().getUser(userID);

然后继续。我在我的 logcat 中收到此错误:

Error: Firebase.child failed: First argument was an invalid path: "/users/${userID}/deviceToken". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
    at Error (native)
    at Ge (/user_code/node_modules/firebase-admin/lib/database/database.js:111:59)
    at R.h.n (/user_code/node_modules/firebase-admin/lib/database/database.js:243:178)
    at Fd.h.gf (/user_code/node_modules/firebase-admin/lib/database/database.js:91:631)
    at exports.sendConnectionNotification.functions.database.ref.onWrite.event (/user_code/index.js:31:51)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

我不明白为什么 Firebase 无法访问该节点。显然,我的路径是有效的。我哪里错了?抱歉,我正好今天才开始学习 Firebase 函数。

**编辑1:** 替换后:

const getDeviceTokensPromise = admin.database().ref('/users/${userID}/deviceToken').once('value');

const getDeviceTokensPromise = admin.database().ref(`/users/${userID}/deviceToken`).once('value');

我遇到了一个新错误。我的控制台日志显示:

There are no notification tokens to send to.

这是我的完整 index.js:

    // // Create and Deploy Your First Cloud Functions


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

    /**
     * Triggers when a user gets a new follower and sends a notification.
     *
     * Followers add a flag to `/followers/{followedUid}/{followerUid}`.
     * Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`.
     */

    exports.sendConnectionNotification = functions.database.ref('/connections/{connectionID}/{userID}').onWrite(event => {

      const parentRef = event.data.ref.parent;
      const userID = event.params.userID;
      const connectionID = event.params.connectionID;

       // If un-follow we exit the function.
      if (!event.data.val()) {
        return console.log('Connection', connectionID, 'was removed.');
      }

      // Get the list of device notification tokens.
      const getDeviceTokensPromise = admin.database().ref(`/users/${userID}/deviceToken`).once('value');

      // Get the user profile.
      const getUserProfilePromise = admin.auth().getUser(userID);

       return Promise.all([getDeviceTokensPromise, getUserProfilePromise]).then(results => {

        const tokensSnapshot = results[0];
        const user = results[1];

        // Check if there are any device tokens.
        if (!tokensSnapshot.hasChildren()) {
          return console.log('There are no notification tokens to send to.');
        }

        console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
        console.log('Fetched user profile', user);

        // Notification details.
        const payload = {
          notification: {
            title: `${user.userNickName} is here!`,
            body: 'You can now talk to each other.'
          }
        };

        // Listing all tokens.
        const tokens = Object.keys(tokensSnapshot.val());

        // Send notifications to all tokens.
        return admin.messaging().sendToDevice(tokens, payload).then(response => {
          // For each message check if there was an error.
          const tokensToRemove = [];
          response.results.forEach((result, index) => {
            const error = result.error;
            if (error) {
              console.error('Failure sending notification to', tokens[index], error);
              // Cleanup the tokens who are not registered anymore.
              if (error.code === 'messaging/invalid-registration-token' ||
                  error.code === 'messaging/registration-token-not-registered') {
                tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
              }
            }
          });
          return Promise.all(tokensToRemove);
        });
   });
});

【问题讨论】:

  • 我不是 firebase 人,但这是您的实际代码与路径('/connections/{connectionID}/{userID}')吗?只是想知道如何在没有 + 的情况下将 connectionID 和 userID 插入实际值,或者在两者之间使用带有 ` 和 ${connections.connectionID}/${userID} 的模板字符串或类似的东西。从您的 sn-p 中,我只看到路径就是那个纯字符串 '/connections/{connectionID}/{userID}'
  • 好吧。我是新手。以此作为参考:github.com/firebase/functions-samples/blob/master/…
  • 哦,好吧! :D 尝试使用 + 或 ` 设置具有所需值的路径。例如'/connections/' + connections.connectionID + '/' + connections.connectionID.userID 这样字符串就有了实际的对象值。或使用 `(模板文字),请在此处阅读这些 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。如果您遇到其他错误,请回复评论。 userID: true 没有多大意义,但我认为它一定只是一个例子。
  • 我认为这是您的问题。从您发布的错误中,'/users/${userID}/deviceToken' 抱怨 $,因为您没有使用 ` ,所以肯定没有被插值,插值不适用于 '。让我们发布:)
  • 我明白了,在参考文献中查看这一行:github.com/firebase/functions-samples/blob/master/… 它使用 `,与 ' 略有不同。很容易混淆。所以从我那里看到的,保持原来的第一个路径不变,并修改那个调用 .value() 的路径。

标签: javascript android firebase firebase-realtime-database firebase-cloud-messaging


【解决方案1】:

您可以使用 (`) 而不是 (') 因为我也遇到了同样的问题并通过使用它来解决。 谢谢

【讨论】:

    【解决方案2】:

    也许您使用的是单引号而不是反引号。 https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

    所以路径没有以正确的方式连接。

    【讨论】:

      【解决方案3】:

      改变

      const getDeviceTokensPromise = admin.database().ref('/users/${userID}/deviceToken').once('value');
      

      const getDeviceTokensPromise = admin.database().ref('/users/' + userID + '${userID}/deviceToken').once('value');
      

      '/users/${userID}/deviceToken' 不是有效路径。 但是'/users/123456/deviceToken',其中123456代表用户ID,是。

      【讨论】:

        猜你喜欢
        • 2017-09-12
        • 2015-01-20
        • 1970-01-01
        • 2018-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        相关资源
        最近更新 更多