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

查看:26
本文介绍了防止 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});

另见:

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

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