问题
We are using Firebase Firestore for data storage. When a user creates a new room, we want the reference to be easy to remember so that a user can share the room ID/code with other users.
At present Firestore will create a unique reference such as: DvfTMYED5cWdo5qIraZg
This is too long and difficult to remember or share. We could set a different reference manually, but they have to be unique. The other point is that users can create multiple rooms so the reference would have to change each time.
Is there a way to use shorter/better references for this use case?
回答1:
Firebase/Firestore has nothing built in for shorter references, as they wouldn't have enough entropy to statistically guarantee uniqueness. But since creating chat rooms is likely a fairly low-volume operation, you can implement this in your app by:
- Generating your own token for each room, for example a counter.
- Checking in the database whether this room is available.
- If the token is already taken, generate another one and try again.
This is pretty much how auto-increment fields work on most databases. On Firestore you'd create a document where you keep the current counter value:
chat_rooms (collection)
COUNTERS: { last_room_id: 2 } (document)
chatroom_1: { room_id: 1, name: "Chat room for Stuart and Frank" } (document)
chatroom_2: { room_id: 2, name: "Public chat room" } (document)
When you now create a new room, you:
- Start a transaction.
- Read
COUNTERS. - Read the
last_room_id, and increment it. - Write the updated document back.
- Create a new document for the new chat room.
- Commit the transaction
Note that there are many ways to generate the codes. The counter approach above is a simple one, but I recommend checking out more options. Some interesting reading:
- How to generate unique coupon codes?
- Generating human-readable/usable, short but unique IDs
- Unique Identifiers that are User-Friendly and Hard to Guess
来源:https://stackoverflow.com/questions/54160254/firebase-firestore-easy-to-remember-references