0

My data of usercollection looks like this:

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

and this is my rule:

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

I just want to read usernames from firestore, if not authenticated to check before registration, if username is already taken. Is this possible. If not, is there another way, like creating a view of all usernames, which i could read from?

Jonathan Sigg
  • 306
  • 3
  • 12

1 Answers1

1

I understand that you want to check if a user document already exists before creating a new one.

A straightforward approach is to maintain a collection of documents with the user name as Document ID and set a security rule like the following one:

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

This collection (usersList) can be the collection where you store the users. But it could also be a collection just dedicated to the verification and the users are contained in another collection.

In this last case you would use a batched write to create the two docs, since batched writes are atomic: If the doc in the usersListRef collection already exists, the new user doc will not be created.

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();
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121