javascript - 在运行嵌套查询的嵌套对象上使用 firebase 云函数搜索数据时未指定索引

标签 javascript node.js firebase firebase-realtime-database

我正在使用 fire-base 检索用户 Node 的嵌套数据,在运行查询时我遇到了从 fire-base 数据库获取数据的问题。

Consider adding ".indexOn": "userId" at /users/YJdwgRO08nOmC5HdEokr1NqcATx1/following/users to your security rules for better performance.

数据库结构:

 "users" : {
    "1vWvSXDQITMmKdUIY7SYoLA1MgU2" : {
      "userEmail" : "test2kawee@gmail.com",
      "userId" : "1vWvSXDQITMmKdUIY7SYoLA1MgU2",
      "userName" : "Malik Abdul Kawee",
      "userPhoneNumber" : "",
      "userProfileImage" : "https://pbs.twimg.com/profile_images/1018741325875867648/ZnKeUiOJ_400x400.jpg"
    },
    "YJdwgRO08nOmC5HdEokr1NqcATx1" : {
      "following" : {
        "1vWvSXDQITMmKdUIY7SYoLA1MgU2" : {
          "currentFollowingUserId" : "YJdwgRO08nOmC5HdEokr1NqcATx1",
          "userEmail" : "test2kawee@gmail.com",
          "userId" : "1vWvSXDQITMmKdUIY7SYoLA1MgU2",
          "userName" : "Malik Abdul Kawee",
          "userPhoneNumber" : "",
          "userProfileImage" : "https://pbs.twimg.com/profile_images/1018741325875867648/ZnKeUiOJ_400x400.jpg"
        }
      },
      "userEmail" : "test2atif@gmail.com",
      "userId" : "YJdwgRO08nOmC5HdEokr1NqcATx1",
      "userName" : "Atif AbbAsi",
      "userPassword" : "test123",
      "userPhoneNumber" : "",
      "userProfileImage" : "http://paperlief.com/images/enrique-iglesias-body-workout-wallpaper-4.jpg"
    }
  }

数据库规则:

    "users": {
     ".indexOn":  ["userId","currentFollowingUserId",".value"],
       "$userId": {
         "following": {
        //"$userId": {
             ".indexOn":  ["userId","currentFollowingUserId",".value"]
        }
    //}
       } 
}

函数查询:

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


exports.sendFollowingNotifications = functions.database.ref('/users/{userId}/following/{followingId}')
       //.onWrite(event => {
         .onCreate((snap,context) => {  


        console.info("Child value is val() " ,snap);


        var childNodeValue=snap.val();

        var topic=childNodeValue.userId;

        //var ref = firebase.database().ref.child('users');

        //console.log("testing ref pathName : " ,snap.ref.parent.parent.parent.pathname);
    //  console.log("testing ref : " ,snap.ref.parent.parent.parent.path);

        //var ref = admin.database().ref("users");

        //.child('users')

        return snap.ref.parent.parent.parent.orderByChild("userId").equalTo(childNodeValue.currentFollowingUserId)

     // .on('child_changed').then(snapshot => { once('value')
         .once('value', function(snapshot){ 
        var parentNodeValue=snapshot.val();

        console.info("Topic ID " ,topic);

        console.info("Parent value is val() " ,snapshot.val());

              var payload = {
            data: {
                username: parentNodeValue.userName,
                imageurl:parentNodeValue.userProfileImage,
                description:"Started Following You"
            }
        };



           // Send a message to devices subscribed to the provided topic.
        return admin.messaging().sendToTopic(topic, payload)
            .then(function (response) {
                // See the MessagingTopicResponse reference documentation for the
                // contents of response.
                console.log("Successfully sent message:", response);
                return response;
            })
            .catch(function (error) {
                console.log("Error sending message:", error);
                return error;
            });

      });








      });

return snap.ref.parent.child('users').orderByChild("userId").equalTo(childNodeValue.currentFollowingUserId)

我认为问题出在这个查询上,我对以下 Node 的第一个查询返回了我的数据,但是当我检索其父 Node 用户的数据时,我收到了警告。

我尝试使用 functions.database.ref 但它给了我以下异常。

so I tried using this `snap.ref.parent.`to get reference of parent node.

Firebase Functions, admin.database().ref(…) is not a function

Firebase Functions, functions.database().ref(…) is not a function

最佳答案

您在阅读用户时得到了错误的引用。您需要执行以下操作才能获得正确的引用:snap.ref.parent.parent.parent(ref 现在位于/users)。您的查询正在尝试读取以下用户 Node 。

警告是您需要编写启用基于 userId 的索引的 firebase 规则,否则该操作将占用大量带宽。

这是添加索引的规则:

"users": {
   "$uid" : {
     ".indexOn" : ["userId"]
   }
}

这里是有关数据库规则的更多信息的资源:https://firebase.google.com/docs/database/security/

这是 firebase 的一个简单工具,可以轻松编写规则:https://github.com/firebase/bolt

P.S:您正在返回两个 promise ,您最后一个发送通知的 promise 将无效。使用 firebase 查询嵌套或链接它。还可以通过将 on('child_changed') 更改为 once('value') 使查询成为单值事件。

关于javascript - 在运行嵌套查询的嵌套对象上使用 firebase 云函数搜索数据时未指定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51853852/

相关文章:

android - 如何在应用程序为后台 FCM 时检索通知消息 intent.getExtras()

javascript - 更新页面数据

node.js - 如何合并两个分支并自动忽略特定文件/文件夹?

javascript - 在我的选项卡面板中获取标题属性

node.js - 默认的 Firebase 应用不存在。确保在使用任何 Firebase 服务之前调用 initializeApp()。在 FirebaseAppError

node.js - S3.getSignedUrl 接受多种内容类型

ios - 如何同时观察两个用户之间的所有 firebase 数据库事件?

swift - 每月重置一个值 - swift 和 firebase

javascript - AngularJS 中 ng-repeat 内的增量计数器

javascript - 从 php 文件中获取 api (GET DATA)