Querying Firestore without Primary Key

Viewed 256

I'd like my users to be able to update the slug on the URL, like so:

url.co/username/projectname

I could use the primary key but unfortunately Firestore does not allow any modifcation on assigned uid once set so I created a unique slug field.

Example of structure:

projects: {
    P10syfRWpT32fsceMKEm6X332Yt2: {
        slug: "majestic-slug",
        ...
    },
    K41syfeMKEmpT72fcseMlEm6X337: {
        slug: "beautiful-slug",
        ...
    },
}

A way to modify the slug would be to delete and copy the data on a new document, doing this becomes complicated as I have subcollections attached to the document.

I'm aware I can query by document key like so:

var doc = db.collection("projects");
var query = doc.where("slug", "==", "beautiful-slug").limit(1).get();

Here comes the questions.

Wouldn't this be highly impractical as if I have more than +1000 docs in my database, each time I will have to call a project (url.co/username/projectname) wouldn't it cost +1000 reads as it has to query through all the documents? If yes, what would be the correct way?

1 Answers

As stated in this answer on StackOverflow: https://stackoverflow.com/a/49725001/7846567, only the document returned by a query is counted as a read operation.

Now for your special case:

doc.where("slug", "==", "beautiful-slug").limit(1).get();

This will indeed result in a lot of read operations on the Firestore server until it finds the correct document. But by using limit(1) you will only receive a single document, this way only a single read operation is counted against your limits.

Using the where() function is the correct and recommended approach to your problem.

Related