Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

android - Generate a unique firestore field

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?

question from:https://stackoverflow.com/questions/65892630/generate-a-unique-firestore-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...