【问题标题】:Firestore rules - Get specific field from documentFirestore 规则 - 从文档中获取特定字段
【发布时间】:2023-02-13 22:08:38
【问题描述】:

我的 usercollection 数据如下所示:

username: "johndoe"
email: "john.doe@test.com"
firstName: "John"
lastName: "Doe"
loginUid: "...."

这是我的规则:

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

我只想从 firestore 中读取用户名,如果在注册前未通过身份验证以检查用户名是否已被占用。 这可能吗。如果没有,是否有另一种方法,比如创建一个我可以读取的所有用户名的视图?

【问题讨论】:

    标签: firebase google-cloud-firestore firebase-security


    【解决方案1】:

    我了解到您想在创建新文档之前检查用户文档是否已经存在。

    一种直接的方法是维护一个文档集合,将用户名作为文档 ID,并设置如下安全规则:

    match /usersList/{userName} {
      allow create: if !exists(/databases/$(database)/documents/usersList/$(userName));
      allow update, delete: if false;
    }
    

    此集合 (usersList) 可以是您存储用户的集合。但它也可以是一个专用于验证的集合,用户包含在另一个集合中。

    在最后一种情况下,您将使用 batched write 创建两个文档,因为批处理写入是原子的:如果 usersListRef 集合中的文档已经存在,则不会创建新的 user 文档。

    const userName = '....';
    
    // Get a new write batch
    const batch = writeBatch(db);
    
    const usersListRef = doc(db, 'usersList', userName);
    batch.set(usersListRef, { ... });
    
    const userRef = doc(db, 'users', userName);
    batch.set(userRef, { ... });
    
    // Commit the batch
    await batch.commit();
    

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 1970-01-01
      • 2018-09-29
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 2020-08-01
      • 2019-03-03
      相关资源
      最近更新 更多