Is it Possible to check if Firebase Firestore documents ID already pressent in collection.

1,807 views
Skip to first unread message

Suraj Sahani

unread,
Mar 4, 2021, 10:47:06 AM3/4/21
to Firebase Google Group
Hi, i want to know if in firebase we can check if document ID is already present in collection before creating new document,  here is document id is my Custom ID.

For example, documents in the collection "Restaurants" have IDs: 0, 1, 2 etc.: 1234, 2244 etc.
So there are Custom ID Entered by User as PIN. so can we check if some pin are already in use like 1234, and 2244 has already set so we don't give option to next user to create document with that ID. is that possible? thanks for any help 


Screenshot from 2021-03-04 20-55-46.png

Sam Stern

unread,
Mar 4, 2021, 10:53:00 AM3/4/21
to Firebase Google Group
Hi Suraj,

The only way to check if a document exists is to try to read it. If you want to make sure that new restaurants don't overlap with old ones I would suggest creating them in a transaction where you first do the read check:
https://firebase.google.com/docs/firestore/manage-data/transactions

Also please note that it's normally best to avoid sequential IDs:
https://firebase.google.com/docs/firestore/best-practices#document_ids

If you can give each restaurant a random ID, that will solve both problems for you!

- Sam

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebase-tal...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/firebase-talk/bef1869e-d6ea-4c06-85ad-8f688139b055n%40googlegroups.com.

Suraj Sahani

unread,
Mar 4, 2021, 11:30:12 AM3/4/21
to fireba...@googlegroups.com
Thank you for replying sam, I'll look into documentation



--
Suraj Sahani
about.me/ssahani

Suraj Sahani

unread,
Mar 4, 2021, 11:34:43 AM3/4/21
to fireba...@googlegroups.com
Sam, I would like to say, I have given each Restaurant their own choice to choose id.
So last time what happened two restaurants choose the same id like 1234 and 1234. and now their data is merged together.
So that's what I'm trying to solve.
Reply all
Reply to author
Forward
0 new messages