DEV Community

Cover image for why use model.findOne({})??
ADJARO OGAGA
ADJARO OGAGA

Posted on

why use model.findOne({})??

Mongodb has undoubtedly become one of the most popular databases used with Nodejs. This is due to the possibility for storing decently, the varied types of data that can be dealt over the internet. For more information on just what mongodb is, and maybe a deep dive please visit their docs at Mongodb Documentation.
But wait!!!
A nerd asking you to wait
At this point I would like you to know that this article is meant for those that have worked with mongodb and maybe a backend framework like nodejs, python or java, its not really for beginners , that not withstanding if you're feeling a little curious please read on, as I would try my very best to make it as down to earth as possible.
Just imagine there is a lorry load of phones, different types, manufacturers. Assuming there is a particular phone you need to get to the owner quickly, you know the make, the type, and details unique to just that phone. Then you start going through each pack, even with just a hundred pack, how tiring that will be!!! phew! I hate stress.. Who doesn't. What if, there was a way to quickly locate just that phone, maybe a magnetic device reader that can read phone types , manufacturers etc. Aha!! Easy right? Would still EVER go through the searching pack by pack way(algorithm)? No sane person will. Fact is, no business man will.
Well, a database. any database as ypou might know a;lready, is a store for unique items. Not phone obviously, but what you ay see on your facebook profile. Your fullname, profile picture, even your posts must all be stored uniquely in a database. Mongodb is one such database. To get you details to your page, the databse has to be searched, just as yoo would search a lorry load of different phones. Just imagine having to search most of the over 5 billion users on facebook before your details comes to your page, that will be a hell of a time.
The good news is, mongodb like most other databases has inner mechanisms, just like the magnetic device you can use to search for a phone's deatils. Actually there are pre-built instructions that ship with mongodb to do the finding for you, they are called methods or functions. One of such is model.findOne(). There is also model.find(). Both do the same thing, but can you guess the difference? If you said findOne searches for one particular item, while find seraches through all untilit finds that one, your'e right.
In summary use model.findOne() for quicker lookup, cleaner syntax. But the emphasis is on "SPEED". With just a few thousands stored data, using any will hardly have any difference. But the world is over 6 billion the last time I checked. So build with that in mind.

Discussion (0)