防止Firestore规则中的重复条目不起作用 [英] Prevent duplicate entries in Firestore rules not working

查看:69
本文介绍了防止Firestore规则中的重复条目不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Google Firestore规则防止重复输入,但是它不起作用.我正在尝试的规则是:

I'm trying to prevent duplicate entries using Google Firestore rules, however it's not working. The rule I'm trying is:

service cloud.firestore {  
  // Prevent duplicate messages
  match /databases/{database}/documents {
    match /messages/{message} {
        allow read;
      allow write: if request.resource.data.m != resource.data.m;
    }
  }
}

从我阅读的内容来看,这应该可行.

From what I read, this should work.

我在做什么错了?

推荐答案

您的规则if request.resource.data.m != resource.data.m说,仅当字段m与字段m 中的当前值不同时才能写入相同的文档.

Your rule if request.resource.data.m != resource.data.m says that field m can only be written if it's not the same as the current value of field m in the same document.

无法按照安全规则检查整个集合中的重复项,因为这将要求Cloud Firestore读取集合中的所有文档(这在规模上会变得非常昂贵).

There is no way to check for duplicates in the entire collection in security rules, as that would require Cloud Firestore to read all documents in the collection (which would become very expensive at scale).

当前唯一实现唯一性约束的方法是创建一个单独的集合,在其中使用m作为文档ID.由于集合中的文档ID在定义上是唯一的,因此您可以在其中强制执行以下规则:

The only way to currently implement a uniqueness constraint is by create a separate collection where you use m as the document IDs. Since document IDs in a collection are by definition unique, you can enforce the rule there with:

match /unique_ms/{m} {
  allow create;
}

以上内容仅允许创建文档,不允许更新文档.这意味着一旦有人创建了特定值m的文档,任何人都无法覆盖它.

The above only allows creating a document, it does not allow updating it. This means that once someone created a document with a specific value of m, nobody can overwrite it.

使用write规则的替代方法可能是:

An alternative using the write rule could be:

allow write: if !exists(/databases/$(database)/documents/unique_ms/{m});

另请参阅:

  • Cloud Firestore: Enforcing Unique User Names
  • firebase rule for unique property in firestore

这篇关于防止Firestore规则中的重复条目不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆