仅当Firebase Firestore中不存在文档时才创建它

编程入门 行业动态 更新时间:2024-10-12 03:27:42
本文介绍了仅当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.

应用流程:

  • 使用Firebase身份验证创建用户(获取UID)
  • 使用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.

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

    更多推荐

    仅当Firebase Firestore中不存在文档时才创建它

    本文发布于:2023-07-21 03:35:58,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1173696.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:时才   中不   文档   Firebase   Firestore

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!