Firebase Firestore Easy to remember references

假装没事ソ 提交于 2021-02-05 07:29:06

问题


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:

  1. Generating your own token for each room, for example a counter.
  2. Checking in the database whether this room is available.
  3. 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:

  1. Start a transaction.
  2. Read COUNTERS.
  3. Read the last_room_id, and increment it.
  4. Write the updated document back.
  5. Create a new document for the new chat room.
  6. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!