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:
1 2 3 4 5 6 7 8 | <script src="https://unpkg.com/ <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> /lodash.min.js"></script> <script src="https://unpkg.com/ <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> /dist/low.min.js"></script> <script src="https://unpkg.com/ <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> /dist/LocalStorage.min.js"></script> <script> var adapter = new LocalStorage('db') var db = low(adapter) </script> |
Create db.js
file content as follows:
1 2 3 4 5 6 7 8 9 | const low = require('lowdb') const FileSync = require('lowdb/adapters/FileSync') const adapter = new FileSync('database.json') const db = low(adapter) db.defaults({ posts: [] }).write() // đoạn này để set default trong file json ta có một mạng posts rỗng module.exports = db |
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:
1 2 3 4 5 6 7 8 9 10 | db.get('posts') .push({ id: 1, title: 'tại sao Tào Tháo lại là gian hùng?', isPublish: false, view: 0, cai_nay_de_xoa: 'No beer, no life' }) .write() |
Get all posts:
1 2 | db.get('posts').value() |
Get an article:
1 2 | db.get('posts').find({id: 1}).value() |
Update article to public
1 2 3 4 5 | db.get('posts') .find({ id: 1 }) .assign({ isPublish: true}) .write() |
Delete article:
1 2 3 4 | db.get('posts') .remove({ id: 1 }) .write() |
Okay, see if there’s anything better than CRUD?
Check if there are any articles
1 2 | db.has('posts').value() |
Get 5 posts and sort posts by views
1 2 3 4 5 6 | db.get('posts') .filter({isPublish: true}) .sortBy('view') .take(5) .value() |
Count the total number of posts:
1 2 | db.get('posts').size().value() |
Delete a property of the article:
1 2 | db.unset('posts.cai_nay_de_xoa').write() |
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
1 2 | const shortid = require('shortid') |
We will replace the create post segment as follows:
1 2 3 4 5 6 7 8 9 | const postId = db .get('posts') .push({ id: shortid.generate(), ... // đoạn này giống như ví dụ bên trên nhé, chỉ là thay id bằng shortid thôi }) .write() .id // sau khi write thì bạn có thể lấy luôn id của post bạn vừa mới thêm vào |
Get the article you just added based on the id of the post you just created:
1 2 3 4 5 | const post = db .get('posts') .find({ id: postId }) .value() |
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:
1 2 | db.get('posts').cloneDeep().value() |
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 (☞ ゚ ヮ ゚) ☞