Executing `Collection.firstWhere().exists()` should return `true` or `false`

exists() does return true or false.

But the return type of first() and firstWhere is a YourDocumentType | Null

image

The exists method only exists on Documents and “NullDocs”. exists() is used to check if a reference is in the database. A NullDoc are like a a pointer we know points at nothing because either it doesn’t exist or you don’t have permission to it. When you use .byId that method either returns a document or NullDoc,

image

A NullDoc is like a bad reference, but it has information about what it is at least trying to look up. The reason we have NullDoc is because this reference may actually point to something in the future, so it is good to keep the Collection and ID info around. You may also want to know that reason (does not exist or no permissions).

When you use first and firstWhere you are requesting a document. It makes sense that if one exists you get it. But what should we do if one does not exist? There is literally nothing to return, not even some reference for you to check if it exists, so we return null.

The type of first and firstWhere is YourDocumentType | Null so you can assume that if it’s not null it’s a document. Don’t use exists() but compare against null.

Question.all().firstWhere(.title.startsWith("old")) != null
1 Like