1

I'm trying to create a system that has 1 person create/delete public rooms while others can join said rooms. Currently it's set up so the host can generate a random room which gets put into firestore as a field:

{
username: Ghost Nappa
room: 2384
}

An issue that I see is that it currently is completely random so sometimes it could try to create a room with a code that's already been generated (and in use) by another. Similar to this post: How to generate and guarantee unique values in firestore collection? the difference being a host has the unique code while the clients would share the code (so it can't be a unique document I don't think) How could I go about checking for one instance of a field across all documents in firestore?

jstoe
  • 137
  • 1
  • 1
  • 6

1 Answers1

1

I understand that in your scenario, several users can have the same room number. You can always check if a room with that number exists by performing a query such as:

// Generate new room number
let newRoomNumber = generateNewRoomNumber();


const docRef = db.collection('users');
const snapshot = await docRef.where('room', '==', newRoomNumber).get();
if (snapshot.empty) {
  console.log('Creating new room');
  createNewRoom();
  return;
}  

Otherwise, the link that @Frank van Puffelen shared shows various ways to address this and also has some nice references

Jose V
  • 1,356
  • 1
  • 4
  • 12