0

Is it possible to ensure uniqueness using multiple document fields.

For example:

In a collection called "books" with documents containing the fields: author, title, and publication date.

new documents should be allowed to have the same author as another document.

new documents could also have the same title as another document.

but, new documents should not be allowed to be written if all three fields are the same as another document in the database.

2 Answers2

1

If you want something to be unique, use it as the ID of your documentation. If you want a combination of values to be unique, use that combination of values as the ID of your documents.

So in your case it sounds like you should use author + title + publication date as the ID of your documents. When you do that, they will by definition be unique.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

The task sounds easy but unfortunately the database rules for both databases in Firebase don't support queries. That means you can't check if a document with a specific field value exists because you can't search for it.

There are two possible solutions you can use to accomplish your task.

1: Create a collection with authors and one for titles where the key is the author name. We write now rules for books that you can't create a document if the request.data.auth && request.data.title exists in those two collections. The next part would be if the creation successes to add the author and title to those two collections to lock them for future aktions. You could do that from client side or even a automated cloud function that would do that for your. Consider that cloud functions can have a cold start and it could take some time that the collectiong get's locked for a author and title.

2: You could create a callable cloud function and send the book data to it. The function would query manually the collection and check if a book with same author and title exists and create one if not.

Tarik Huber
  • 7,061
  • 2
  • 12
  • 18