Lowdb solution for using compact database for pet projects with Nodejs, Electron.

Tram Ho

Hi everyone, today I would like to introduce to you a very handy item when making pet projects with nodejs, that is lowdb.

Concept

What is lowdb: is a small JSON database for node, electron or browser applications, more simply, lowdb allows you to save the JSON database as a file or maybe also localstorage.

What is lowdb: it is provided by lodash, so if you are familiar with lodash, using lowdb is also extremely easy, and lowdb also allows you to customize the adapter (I rarely use this) or encrypt data

How to use lowdb

Initialize lowdb

For node / electron applications: npm install lowdb or yarn add lowdb

Or browser:

Create db.js file content as follows:

A database.json file will be created for you at the root directory, to change the path to another directory you just need to fix the following code:

new FileSync('database.json') => new FileSync('folder-name/database.json')

Note: here we use JSON files to save, you can also use localStorage to replace FileSync adapter

lowdb is ready for use.

Let’s start with CRUD

Add a new article:

Get all posts:

Get an article:

Update article to public

Delete article:

Okay, see if there’s anything better than CRUD?

Check if there are any articles

Get 5 posts and sort posts by views

Count the total number of posts:

Delete a property of the article:

Well, here you may realize, if the ID number as I write it is probably quite bananas, so you have 2 other options to replace the increment id yourself by adding 1 to the last id by Use shortid or lodash-id .

For example, using the shortid After installing you need to import into the post creation area first

We will replace the create post segment as follows:

Get the article you just added based on the id of the post you just created:

Note when using lowdb

  • The database is saved as a JSON file, so when the file is too large, there may be problems
  • The returned data is a reference, so when you get a list of posts and add an attribute or delete or do something, the db will update itself too, so you need to use .cloneDeep() to avoid this. occur when not needed

For example:

When I used it wrongly but I did not know because I did not read this section carefully, I fixed it by clone from the data that I took out, it is always necessary to read the instructions carefully before using that

Conclusion

Through the article I would like to briefly introduce about lowdb a tool to help implement pet projects or test something new in your project without the lowdb of installing and configuring lengthy db databases.

There are many interesting features that I have not tried and also difficult to write because they are quite long, so I temporarily introduce through the basic features that you can use with lowdb .

Lowdb’s Git repo: https://github.com/typicode/lowdb

Thank for your time, bro (☞ ゚ ヮ ゚) ☞

Share the news now

Source : Viblo