Introduction to lowdb
Lowdb is a small local JSON database powered by Lodash. It’s a simple and efficient way to persist data locally, without needing a large and complex database setup. Perfect for quick prototypes and small projects, lowdb allows you to read and write JSON data effortlessly.
In this article, we’ll explore various lowdb APIs and how to utilize them effectively. Let’s dive in!
Getting Started with lowdb
const low = require('lowdb'); const FileSync = require('lowdb/adapters/FileSync'); const adapter = new FileSync('db.json'); const db = low(adapter); // Set some defaults db.defaults({ posts: [], user: {}, count: 0 }) .write();
Basic CRUD Operations
Create and Insert Data
// Add a new post db.get('posts') .push({ id: 1, title: 'lowdb is awesome' }) .write();
Read Data
// Get all posts const posts = db.get('posts') .value(); // Get a single post by id const post = db.get('posts') .find({ id: 1 }) .value();
Update Data
// Update a post title db.get('posts') .find({ id: 1 }) .assign({ title: 'lowdb is super awesome' }) .write();
Delete Data
// Remove a post db.get('posts') .remove({ id: 1 }) .write();
Additional Useful API Examples
Handling Arrays
// Increment count db.update('count', n => n + 1) .write();
Using Lodash Functions
// Get the total number of posts const postCount = db.get('posts').size().value(); // Get titles of all posts const titles = db.get('posts').map('title').value();
Working with Nested Data
// Set user details db.set('user.name', 'typicode') .set('user.age', 30) .write(); // Update nested data db.update('user.age', n => n + 1) .write();
App Example Using lowdb
Below is an example of a simple note-taking application using lowdb:
const express = require('express'); const low = require('lowdb'); const FileSync = require('lowdb/adapters/FileSync'); const app = express(); const adapter = new FileSync('notes.json'); const db = low(adapter); db.defaults({ notes: [] }).write(); app.use(express.json()); app.get('/notes', (req, res) => { const notes = db.get('notes').value(); res.send(notes); }); app.post('/notes', (req, res) => { const note = req.body; db.get('notes').push(note).write(); res.send(note); }); app.delete('/notes/:id', (req, res) => { const id = req.params.id; db.get('notes').remove({ id: id }).write(); res.send({ success: true }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
With this setup, you can start building more flexible and advanced functionality using lowdb.
Hash: 562a51e2b9fe91f7adf3806877a0943977446a9919068f410c6461d1bb6f2f31