仅当Firebase Firestore中不存在文档时才创建它 [英] Create a document only if it doesn't exist in Firebase Firestore

查看:49
本文介绍了仅当Firebase Firestore中不存在文档时才创建它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现的目标非常简单.只有在数据库中不存在用户条目时,我才需要创建它.

What I am trying to achieve is very simple. I need to create a user entry in the database only if it doesn't exist.

应用流程:

  1. 使用Firebase身份验证创建用户(获取UID)
  2. 使用UID作为键在数据库中创建用户文档

客户端代码(创建操作):

this.db.doc('users/' + uid).set({username: Santa})

firestore规则:

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow create: if 
        request.auth != null && 
        request.auth.uid == uid && 
        !exists(/databases/$(database)/documents/users/$(uid));
      allow update: if request.auth != null && request.auth.uid == uid; 
    }
  }
} 

其他信息:

您可能已经知道该代码无效.每次我运行客户端代码时,当前用户都会被新文档完全替换.但是,如果我从规则中删除以下行,则一切都会按预期进行:

As you may already know the code doesn't work. Everytime I run the client-side code the current user is completely replaced with a new document. However, if I delete the following line from the rules everything works as expected:

allow update: if request.auth != null && request.auth.uid == uid;

但是现在出现了问题,如何保护用户文档中的数据免遭未经授权的修改?有什么建议吗?

But now the question arises, how do I secure data inside user document from unauthorised modifications? Any advice?

推荐答案

如果仅在尚不存在的情况下仅允许创建文档,则使用已经存在的 allow create 规则有.由于您还具有 allow update 规则,因此也允许更新现有数据.

If you want to allow creating a document only if it doesn't already exist, just use the allow create rule that you already have. Because you also have an allow update rule, updating the existing data is also allowed.

以下规则应足够:

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow create: if request.auth != null && request.auth.uid == uid;
    }
  }
} 

您不需要 exists()调用,因为 allow create 仅在数据不存在的情况下适用.

You don't need the exists() call, because allow create only applies if the data does not exist.

现在,您的问题是:您应该明确说明您的意思.现在,只有经过身份验证的用户才能修改自己的记录.如果您不想允许写入任意数据,请检查它.

Now to your question: You should clarify what you mean exactly. Now only the authenticated user can modify its own record. If you don't want to allow arbitrary data to be written, check for it.

以下是一些示例: https://firebase.google.com/docs/firestore/security/rules-conditions#authentication

这篇关于仅当Firebase Firestore中不存在文档时才创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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