0

In my current database design, I want to read and write to messages subcollection of chat collection, but I want to ensure whether the chat id exists or not. Chat ID is of the form user1refID_user2refID. If chat ID doesn't exist I want to create a new one and trigger cloud function to assign UIDs to member 1 and member 2 fields of chat documents by using a mapping from refID to UserID. In my security rules, I am checking whether incoming user ID is equal to member 1 uid or member 2 uid if the document already exists but how do I make sure that security rule wouldn't fail for the first time. In simple words, I want to check whether document ID exists or not but also do not allow read/write access after the document is created. Is this even possible?

My code looks like this https://stackoverflow.com/a/46965065/10807253 right now.

enter image description here

tensor
  • 733
  • 1
  • 13
  • 22

1 Answers1

0

It's not possible. Firestore doesn't offer any checks for existence. You will have to read the document in order to know if it exists. You might want to have an empty document in a another collection with the same ID but different security rules that you can check for existence by reading it.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thanks for the answer. Yes another subcollection idea is good but then I have to check everytime while writing any message or reading right? Also, is this the correct approach for adding chat feature? – tensor Apr 19 '20 at 07:11