Simple node.js database solution based off lodash called lowdb.
When it comes to database solutions that are popular in a node.js environment the first project that comes to mind is of course mongoDB. I am no database expert, it strikes me as a decent solution, but it might not be the best tool for the job with simple projects. Also It complicates the process of deployment, and setup as another application besides node needs to be installed. Thats why a simpler solution like lowdb is sometimes what a project calls for.
getting started with lowdb
My procedure for setting up a test project goes like this:
I often uses git as a means of source control, and publish my test projects to my github account now. Also if you do not know by now using the –save option when calling npm install will add it to the package.json file of a node.js project.
Now that I have a test folder I can start writing a few demos using this project, lets start with the usual basic one.
Basic lowdb hello world example
In my basic example I just wanted to see how easy it is to make a json file from a single object, and it is pretty easy. Still in order to use lowdb I need not just a reference to the module itself, but also an adapter for reading and writing to the json file. Luck for me one is included that seems to work just fine.
I will want to always set, and write some defaults for the database. The defaults will make sure that whatever I am grabbing at later will be there in some form, even if it is just an empty array. This is also a way of defining what the collections will be to be used with methods like the db.get method used in the example.
The above example gives me the following db.json file
Find something in a database
This project is powered by lodash a subject that I have wrote a few posts on including the find method in lodash. The same method is used in lowdb to find an object in a collection, so if you are comfortable with _.find then getting an object in a collection should be pretty easy for you.
I should at least also cover a basic example of how to update an object in a collection in lowdb. It just involves using find, and assign, then finishing with write like so:
This demo should write a single object to the collection users if it is empty, and every time get and update the single record with a count, and date.
Do not forget to call .value()
When getting a collection or a query for something I need to call value otherwise I am not going to get what I might expect.
This project seems to be just what it was that I was looking for when it comes to a simple, easy to use database solution. I will be using this in a pet project of mine, as such I may be writing about this a great deal more in the future, for now hopefully this post still provides at least some value. In the mean time the readme on lowdb helps explain the basics more as well.