Introduction to Lowdb
Lowdb is a small local JSON database for Node.js, perfect for small projects and for situations where a full-fledged database is overkill. Lowdb provides a simple API for reading and writing JSON data and is powered by Lodash, making it versatile and highly optimized.
Installing Lowdb
npm install lowdb
Creating a Simple Database
To begin, you need to include Lowdb and create an instance.
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync('db.json');
const db = low(adapter);
Setting Default Values
You can set some default values if your JSON file is empty.
db.defaults({ posts: [], user: {}, count: 0 }).write();
Writing Data
Adding new data to the database is simple.
db.get('posts')
.push({ id: 1, title: 'Lowdb is awesome!' })
.write();
Reading Data
You can also read data from the database easily.
const posts = db.get('posts').value();
console.log(posts);
Updating Data
Updating existing data is straightforward.
db.get('posts')
.find({ id: 1 })
.assign({ title: 'Lowdb is powerful!' })
.write();
Removing Data
Removing data by filtering out what you don’t need.
db.get('posts')
.remove({ id: 1 })
.write();
Using Third-Party Adapters
You can switch to other storage solutions using different adapters.
const Memory = require('lowdb/adapters/Memory');
const adapterMemory = new Memory();
const dbMemory = low(adapterMemory);
API Examples with Applications
Let’s see how you can use Lowdb in a simple application.
const express = require('express');
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const app = express();
const adapter = new FileSync('db.json');
const db = low(adapter);
db.defaults({ posts: [], user: {}, count: 0 }).write();
app.use(express.json());
app.get('/posts', (req, res) => {
const posts = db.get('posts').value();
res.json(posts);
});
app.post('/posts', (req, res) => {
const newPost = req.body;
db.get('posts')
.push(newPost)
.write();
res.json(newPost);
});
app.put('/posts/:id', (req, res) => {
const { id } = req.params;
const updatedPost = req.body;
db.get('posts')
.find({ id: parseInt(id, 10) })
.assign(updatedPost)
.write();
res.json(updatedPost);
});
app.delete('/posts/:id', (req, res) => {
const { id } = req.params;
db.get('posts')
.remove({ id: parseInt(id, 10) })
.write();
res.status(204).send();
});
app.listen(3000, () => console.log('Server listening on port 3000'));
In this example, an Express.js server uses Lowdb to manage posts. The server supports CRUD operations with Lowdb, demonstrating how powerful and easy-to-use Lowdb is for fast and lightweight applications.
Hash: 562a51e2b9fe91f7adf3806877a0943977446a9919068f410c6461d1bb6f2f31