Firebase 警告:使用 Firebase Cloud Function 搜索数据时使用未指定的索引

Adi*_*ari 4 javascript firebase firebase-realtime-database google-cloud-functions

我构建了一个 Firebase 云函数,用于查找 'IsNotificationEnabled' 值等于 true 的用户。我的功能的一部分

export const sendPushNotification = functions.https
.onRequest(async (req, res) => {
    try {
        const { message } = req.body;
        var usersRef = firebase.ref('/Users');
        var usersPushNotificationTokensRef = firebase.ref('/PushNotificationTokens')

        var listUsersSendNotifications = [],
            usersWithTokenSendNotifications = [],
            promises = [];
        if (message) {
            await usersRef.orderByChild('IsNotificationEnabled').equalTo(true).once('value', (snapshot) => {
                snapshot.forEach((childSnapshot) => {
                    console.log(childSnapshot.key)
                    listUsersSendNotifications.push(childSnapshot.key)

                    return false;
                })
            })
            ..........................
Run Code Online (Sandbox Code Playgroud)

正如您在这里看到的,我正在寻找 IsNotificationEnabled = true 的用户。当我运行它时,我进入日志

[2018-05-22T09:12:57.352Z] @firebase/database: FIREBASE 警告:使用未指定的索引。您的数据将在客户端下载和过滤。考虑将 /Users 处的 ".indexOn": "IsNotificationEnabled" 添加到您的安全规则以获得更好的性能。

我在 firebase 控制台中插入的规则

    {
  "rules": {
     ".indexOn": ["IsNotificationEnabled"],

    "Users":{
      "$uid":{
      ".indexOn": ["IsNotificationEnabled"],
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid"
      }


    },
    ".read": true,
    ".write": true
  }
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*len 7

正如消息所述,您需要将索引添加到/Users. 您现在将它添加到低一级,在那里它不起作用。

{
  "rules": {
    "Users":{
      ".indexOn": ["IsNotificationEnabled"]
    },
    ".read": true,
    ".write": true
  }
}
Run Code Online (Sandbox Code Playgroud)

我发现通过考虑在哪里运行查询,最容易记住在哪里定义索引。由于您的查询在 上运行/Users,您需要在该级别定义索引。

我还删除了您的.read.write规则/Users/$uid,因为它们无效。您已经在根目录授予完全读/写访问权限,并且不能在较低级别取消权限。

  • 请注意,删除根 `".read": true` 将确保您的查询失败,因为 [规则不是过滤器](https://firebase.google.com/docs/database/security/securing-data#rules_are_not_filters) . 如果你希望能够从 `/Users` 读取,你必须对 `/Users` 具有读取权限。 (2认同)