Examples
Complete real-world examples showing how to use low-json-db effectively.
Complete CRUD Example
const { JSONDB } = require('low-json-db');
const db = new JSONDB('./data');
const users = db.collection({
name: 'users',
autoId: true,
indexes: ['email']
});
// Create
const alice = users.insert({
name: 'Alice',
email: 'alice@example.com',
age: 28,
tags: ['admin']
});
// Read
const found = users.findOne({ email: 'alice@example.com' });
// Update
users.updateOne(
{ name: 'Alice' },
{ $set: { age: 29 }, $push: { tags: 'founder' } }
);
// Delete
users.deleteOne({ name: 'Alice' });
Using Transactions
const tx = users.startTransaction();
try {
tx.insert({ name: 'Bob', email: 'bob@example.com' });
tx.insert({ name: 'Carol', email: 'carol@example.com' });
await tx.commit();
} catch (err) {
await tx.rollback();
}
Async Server Style
app.post('/users', async (req, res) => {
const user = await users.insertAsync(req.body);
res.json(user);
});
app.get('/users/:email', async (req, res) => {
const user = await users.findOneAsync({ email: req.params.email });
res.json(user || { error: 'Not found' });
});
You now have a complete understanding of low-json-db.
Happy coding!