Is it possible in Firestore to define an index with a unique constraint? If not, how is it possible to enforce uniqueness on a document field (without using document ID)?
相关问题
- Firebase security rules difference between get() a
- Firebase firestore not working with Angular Univer
- Firestore limit writing access per time
- MappedListIterable is not a SubType
- How to use arrayUnion with AngularFirestore?
相关文章
- Firestore Update a document field Using Rest API
- How to combine Firestore orderBy desc with startAf
- Firestore + cloud functions: How to read from anot
- Checking if a document exists in a Firestore colle
- Flutter how to use Future return value as if varia
- Flutter Firestore add new document with Custom ID
- Display duplicate events after update firestore da
- Firestore - get specific fields from document
Yes, this is possible using a combination of two collections, Firestore rules and batched writes.
https://cloud.google.com/firestore/docs/manage-data/transactions#batched-writes
The simple idea is, using a batched write, you write your document to your "data" collection and at the same write to a separate "index" collection where you index the value of the field that you want to be unique.
Using the Firestore rules, you can then ensure that the "data" collection can only have a document written to it if the document field's value also exists in the index collection and, vice versa, that the index collection can only be written to if value in the index matches what's in the data collection.
Example
Let's say that we have a
User
collection and we want to ensure that theusername
field is unique.Our
User
collection will contain simply theusername
Our
Index
collection will contain the username in the path and avalue
property that contains the id of the User that is indexed.To create our
User
we use a batch write to create both theUser
document and theIndex
document at the same time.To update our
User
's username we use a batch write to update theUser
document, delete the previousIndex
document and create a newIndex
document all at the same time.To delete a
User
we use a batch write to delete both theUser
document and theIndex
document at the same time.We then setup our Firestore rules so that they only allow a
User
to be created if the username is not already indexed for a differentUser
. AUser
's username can only be updated if anIndex
does not already exist for the username and aUser
can only be deleted if theIndex
is deleted as well. Create and update will fail with a "Missing or insufficient permissions" error if aUser
with the sameusername
already exists.[Its not a perfect solution but working]
I have done this unique key using key... I want my table to be having unique date value. so i made it key of my document. Any way i am able to get all documents