[Feature] Model.exists(query)
See original GitHub issueI found myself using this pattern a lot, where I want to know whether a document exists or not.
const user = await User.findOne({ name: 'Hafez' }).select('_id').lean();
if (user) {
// do stuff
}
It works, but I find it unnecessarily verbose, if this is a common pattern, we could have a function that does the same thing under the hood, and returns true
or false
. Maybe something like
const userExists = await User.exists({ name: 'Hafez' }); // returns true or false
if (userExists) {
// do stuff
}
Meanwhile, I was wondering if .select('_id').lean();
is the most performant way to find if a document exists, some insight here would be greatly appreciated.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:12
- Comments:15 (1 by maintainers)
Top Results From Across the Web
Django exists() versus DoesNotExist - python - Stack Overflow
The DoesNotExist exception for a model is raised when you actually attempted to retrieve one instance, and it didn't exist.
Read more >The Exists Query in Spring Data - Baeldung
The idea is to execute a case-insensitive count query based on the model property, evaluate the return value, and map the result to...
Read more >Exists query | Elasticsearch Guide [8.5] | Elastic
Exists query edit. Returns documents that contain an indexed value for a field. An indexed value may not exist for a document's field...
Read more >The mongoose exists function - ObjectRocket
The exists() method returns a boolean value, i.e. either true or false. This method checks if a particular document exists in a collection...
Read more >QuerySet API reference | Django documentation
It builds on the material presented in the model and database query guides, ... (and don't need the actual objects), it's more efficient...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
In the meantime, I’m using this code just to reduce verbosity:
This lets me run this code:
@num8er
findOne()
is more performant thancount()
in this case, unless your network is extremely slow and a couple bytes matter. Becausecount()
behaves similarly tofind()
in that it doesn’t stop after it finds a matching doc, so if there’s no index thencount()
will always do a full collection scan.