如何在 @angular/fire 7&#x2B中使用CollectionGroup

发布于 2025-01-23 11:09:48 字数 1570 浏览 6 评论 0 原文

我会使用关键字做搜索表格,可以使用更古老的 @angular/fire进行搜索,但不能使用它来进行。

总是相同的错误:

FirebaseError:丢失或不足的权限

,但它显示了上面的错误。

然后,我尝试创建一个firebase函数来返回我的收集组,但是由于它不是 @angular/fire,所以我无法重复使用该对象,它纯粹是firebase,对吗?

在我的组件中:

import {
  collectionData,
  collectionGroup,
  DocumentData,
  Firestore,
  query,
  where,
} from '@angular/fire/firestore';

search() {
if (this.searchForm.value.search.length) {
  let substances = collectionGroup(this.afStore, 'substance');
  // ERROR FirebaseError: Missing or insufficient permissions.
  let query$ = query(
    substances,
    where('keywordsName', 'array-contains', this.searchForm.value.search)
  );
  let res = collectionData(query$);
  let res$ = res.pipe(
    map((families: DocumentData[]) => {
      families.forEach((family: DocumentData) => {
        family['color'] = this.riskReduction.generateRandomColor();
      });
      return families;
    })
  );
  this.riskReduction.setSubstances(res$);
} else {
  this.riskReduction.setSubstances(this.riskReduction.getSubstances());
}
}

编辑: 否则我尝试了该功能:

/**
 * ANCHOR: Search a substance
 */

export const searchSubstance = functions.https.onCall(async (data, context) => {
  try {
    const ref = admin.firestore().collectionGroup('substance');
    return <BasicResponse>{
      status: 'success',
      data: { substances: ref.get() },
    };
  } catch (e) {
    console.log(e);
    return <BasicResponse>{ status: 'error', message: e };
  }
});

感谢您的帮助

I would do a search form using keywords, I can do it with more ancient versions of @angular/fire but not with this one.

Always the same error :

FirebaseError : missing or insufficient permissions

I've tried to implement a collectionGroup new function inside my Angular app but it shows the error above.

Then I've tried to create a firebase function to return my collectionGroup but I can't re-use the object because it's not @angular/fire, it's purely firebase, right ?

Inside my component :

import {
  collectionData,
  collectionGroup,
  DocumentData,
  Firestore,
  query,
  where,
} from '@angular/fire/firestore';

search() {
if (this.searchForm.value.search.length) {
  let substances = collectionGroup(this.afStore, 'substance');
  // ERROR FirebaseError: Missing or insufficient permissions.
  let query$ = query(
    substances,
    where('keywordsName', 'array-contains', this.searchForm.value.search)
  );
  let res = collectionData(query$);
  let res$ = res.pipe(
    map((families: DocumentData[]) => {
      families.forEach((family: DocumentData) => {
        family['color'] = this.riskReduction.generateRandomColor();
      });
      return families;
    })
  );
  this.riskReduction.setSubstances(res$);
} else {
  this.riskReduction.setSubstances(this.riskReduction.getSubstances());
}
}

Edit :
Else I tried with the function :

/**
 * ANCHOR: Search a substance
 */

export const searchSubstance = functions.https.onCall(async (data, context) => {
  try {
    const ref = admin.firestore().collectionGroup('substance');
    return <BasicResponse>{
      status: 'success',
      data: { substances: ref.get() },
    };
  } catch (e) {
    console.log(e);
    return <BasicResponse>{ status: 'error', message: e };
  }
});

thanks for your help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

桃扇骨 2025-01-30 11:09:48

错误:

许可证:丢失或不足的权限

表示此例外是因为firebase服务器拒绝了操作,因此可以通过更改云firestore安全规则
您可以尝试以下规则(仅用于测试):

rules_version = '2';
service cloud.firestore {
 match /databases/{database}/documents {
   match /{document=**} {
     allow read, write: if true;
   }
 }
}

仅推荐规则用于测试目的,因为任何具有您的项目ID的人都可以读取或写入。您可以实施多种安全措施,以下是出色的文章 Alex Mamo(社区成员),您可以用来实施其他几个更安全的安全规则。

1st UPDATE

Since we are retrieving results from a 收集小组由收藏组成,您需要使用

当使用递归通配符语法时,即使文档位于深度嵌套的子采集中,通配符变量也将包含整个匹配路径段。例如,上面列出的规则将与位于/coties/sf/landmarks/coit_tower 的文档匹配,并且文档变量的值将为 sf/landmarks/coit_tower

在安全规则的第2版中,递归通配符与零或更多路径项目匹配。 match/cities/{city}/{document = **} 匹配 Cities 集合中的任何子收集和文档中的文档。

您必须通过添加Rules_version ='2'选择输入版本2;在您的安全规则的顶部:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Matches any document in the cities collection as well as any document
    // in a subcollection.
    match /cities/{city}/{document=**} {
      allow read, write: if <condition>;
    }
  }
}

您最多可以每次匹配声明中拥有一个递归的通配符,但是在版本2中,您可以将此通配符放在匹配语句中的任何位置。例如:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Matches any document in the songs collection group
    match /{path=**}/songs/{song} {
      allow read, write: if <condition>;
    }
  }
}

我们可以通过实现 firebase admin sdk ,这

我还发现此 github theard 这解释了如何避免避免在此错误上遇到此错误。如下:

  1. 转到IAM,然后
  2. 在“项目名称的服务
  3. 帐户” [项目名称]'在其名称列中复制具有“ App Engine默认服务帐户”的帐户的电子邮件(应应be [project_id]@appspot.gserviceaccount.com)。
  4. 从左侧单击左侧
  5. 单击 +在“新校长”粘贴的“'iam'标题”的顶部('iam'标题旁边)
  6. 中的iam菜单粘贴在第3点复制的服务帐户电子邮件中,
  7. 选择'firebase admin SDK管理员服务代理
  8. 单击“保存”。

The error:

PERMISSION_DENIED: Missing or insufficient permissions

Means that this exception is thrown because the Firebase servers rejected the operation, this can be fixed by changing the Cloud Firestore Security Rules
You can try the following rules (only for testing):

rules_version = '2';
service cloud.firestore {
 match /databases/{database}/documents {
   match /{document=**} {
     allow read, write: if true;
   }
 }
}

The rules are only recommended for testing purposes since anyone that has your project ID can read or write. You can implement several security measures, here is an excellent article by Alex Mamo (a member of the community) that you can use to implement several other more secure security rules.

1st UPDATE

Since we are retrieving results from a collection group consisting of collections, you need to use recursive wildcard {name=**}

When using the recursive wildcard syntax, the wildcard variable will contain the entire matching path segment, even if the document is located in a deeply nested subcollection. For example, the rules listed above would match a document located at /cities/SF/landmarks/coit_tower, and the value of the document variable would be SF/landmarks/coit_tower.

In version 2 of the security rules, recursive wildcards match zero or more path items. match/cities/{city}/{document=**} matches documents in any sub-collections and documents in the cities collection.

You must opt-in to version 2 by adding rules_version = '2'; at the top of your security rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Matches any document in the cities collection as well as any document
    // in a subcollection.
    match /cities/{city}/{document=**} {
      allow read, write: if <condition>;
    }
  }
}

You can have at most one recursive wildcard per match statement, but in version 2, you can place this wildcard anywhere in the match statement. For example:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Matches any document in the songs collection group
    match /{path=**}/songs/{song} {
      allow read, write: if <condition>;
    }
  }
}

We can avoid this error altogether by implementing Firebase Admin SDK, this will bypass the security rules entirely.

I also find this github theard that explains how to avoid getting this error doing the following:

  1. Go to IAM and admin
  2. Select the Service accounts menu on the left hand side
  3. Under 'Service accounts for project '[Project Name]' copy the Email of the account that has 'App Engine default service account' under its Name column (should be [project_id]@appspot.gserviceaccount.com).
  4. Select the IAM menu from the left hand side
  5. Click +ADD on the very top (next to the 'IAM' title)
  6. In the field 'New principals' paste the service account email copied in point 3
  7. Select the role 'Firebase Admin SDK Administrator Service Agent'
  8. Click SAVE.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文