【问题标题】:Firebase warning: Using an unspecified index when search data with Firebase Cloud FunctionFirebase 警告:使用 Firebase Cloud Function 搜索数据时使用未指定的索引
【发布时间】:2021-12-31 00:17:25
【问题描述】:

我构建了一个 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;
                })
            })
            ..........................

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

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

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

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

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


    },
    ".read": true,
    ".write": true
  }
}

【问题讨论】:

  • 我在你的问题中遗漏了这个问题。但是 indexon 不需要更高一级吗?在用户下方而不是 $uid。
  • 我的问题,为什么我会收到这个错误以及如何解决它。我编辑了我的帖子并添加了用户结构的图像
  • 您是否尝试将 indexon 放在 users 下方而不是 $uid 下方?
  • 是的,现在可以使用了。谢谢你,先生。

标签: javascript firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

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

{
  "rules": {
    "Users":{
      ".indexOn": ["IsNotificationEnabled"]
    },
    ".read": true,
    ".write": true
  }
}

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

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

【讨论】:

  • 嘿,我想明白。我将删除对 root 的读写,因为我希望只有具有 uid 的用户可以读写。此外,当我从 firebase 函数读取数据时,我是否需要按照您在答案中显示的内容进行编写?因为 isNotificationEnabled 在我的应用程序中的每个用户 ID 下。用户/random_key/isNotificationEnabled
  • 正如我所说:您需要在运行查询的地方定义索引。由于您查询/Users,因此您需要将索引添加到/Users
  • 请注意,删除根 ".read": true 将确保您的查询失败,因为 rules are not filters。如果您希望能够从/Users 读取,您必须对/Users 具有读取权限。
猜你喜欢
  • 2019-04-19
  • 2021-01-14
  • 2017-10-08
  • 2021-11-10
  • 2021-09-28
  • 2019-01-22
  • 2019-02-20
  • 1970-01-01
相关资源
最近更新 更多