jdb-lite
A lightweight, zero-dependency JSON database for Node.js with a familiar API. Perfect for small projects, prototyping, or when you need a simple file-based database without the complexity of traditional databases.
✨ Features
- 🔄 Familiar API - Mongoose-like interface that feels natural
- 📁 JSON File Storage - Data stored in simple JSON files
- 🔧 Schema Validation - Define and validate your data structure
- 📦 Multi-format Support - Works with CommonJS, ES Modules, TypeScript, and JavaScript
- 🔍 Full CRUD Operations - Create, Read, Update, Delete with filtering and sorting
- 🎯 TypeScript Support - Full type safety and IntelliSense
- ⚡ Zero Dependencies - Lightweight with no external dependencies
- 🚀 Easy Setup - Get started in minutes
📦 Installation
npm install jdb-lite
🚀 Quick Start
JavaScript (CommonJS)
const JsonDB = require('jdb-lite');
const { Schema } = require('jdb-lite');
const userSchema = new Schema({
name: { type: 'String', required: true },
email: { type: 'String', required: true },
age: { type: 'Number', required: true },
isActive: { type: 'Boolean', default: true }
});
async function main() {
await JsonDB.connect('./my-database');
const User = JsonDB.model('User', userSchema);
const user = new User({
name: 'John Doe',
email: 'john@example.com',
age: 30
});
await user.save();
console.log('User saved!', user);
}
main();
JavaScript (ES Modules)
import JsonDB, { Schema } from 'jdb-lite';
const userSchema = new Schema({
name: { type: 'String', required: true },
email: { type: 'String', required: true },
age: { type: 'Number', required: true }
});
await JsonDB.connect('./my-database');
const User = JsonDB.model('User', userSchema);
const user = await User.create({
name: 'Jane Doe',
email: 'jane@example.com',
age: 25
});
console.log('User created!', user);
TypeScript
import JsonDB, { Schema, Document } from 'jdb-lite';
interface IUser extends Document {
name: string;
email: string;
age: number;
isActive?: boolean;
}
const userSchema = new Schema<IUser>({
name: { type: 'String', required: true },
email: { type: 'String', required: true },
age: { type: 'Number', required: true },
isActive: { type: 'Boolean', default: true }
});
await JsonDB.connect('./my-database');
const User = JsonDB.model<IUser>('User', userSchema);
const user: IUser = await User.create({
name: 'Alice Smith',
email: 'alice@example.com',
age: 28
});
📖 Complete Usage Guide
1. Connection
await JsonDB.connect('./my-database');
await JsonDB.connect('/path/to/database');
await JsonDB.disconnect();
2. Schema Definition
const userSchema = new Schema({
name: {
type: 'String',
required: true,
default: 'Anonymous'
},
age: {
type: 'Number',
required: true,
validate: (value) => value >= 0
},
isActive: {
type: 'Boolean',
default: true
},
createdAt: {
type: 'Date',
default: Date.now
},
tags: {
type: 'Array',
default: []
},
settings: {
type: 'Object',
default: {}
}
}, {
timestamps: true,
collection: 'users'
});
3. Creating Documents
const user = new User({
name: 'John Doe',
email: 'john@example.com',
age: 30
});
await user.save();
const user = await User.create({
name: 'Jane Doe',
email: 'jane@example.com',
age: 25
});
const users = await User.insertMany([
{ name: 'User 1', email: 'user1@example.com', age: 20 },
{ name: 'User 2', email: 'user2@example.com', age: 30 }
]);
4. Reading Documents
const allUsers = await User.find();
const adults = await User.find({ age: { $gte: 18 } });
const activeUsers = await User.find({ isActive: true });
const user = await User.findOne({ email: 'john@example.com' });
const user = await User.findById('507f1f77bcf86cd799439011');
const users = await User.find({ age: { $gte: 25 } })
.sort({ age: -1 })
.limit(10)
.skip(5);
const count = await User.countDocuments({ isActive: true });
5. Updating Documents
await User.updateOne(
{ email: 'john@example.com' },
{ age: 31 }
);
await User.updateMany(
{ isActive: false },
{ isActive: true }
);
const updatedUser = await User.findOneAndUpdate(
{ email: 'john@example.com' },
{ age: 32 },
{ new: true }
);
const user = await User.findByIdAndUpdate(
'507f1f77bcf86cd799439011',
{ name: 'John Smith' },
{ new: true }
);
6. Deleting Documents
await User.deleteOne({ email: 'john@example.com' });
await User.deleteMany({ isActive: false });
const deletedUser = await User.findOneAndDelete({ email: 'john@example.com' });
const user = await User.findByIdAndDelete('507f1f77bcf86cd799439011');
7. Instance Methods
const user = await User.findOne({ email: 'john@example.com' });
console.log(user.isNew);
user.age = 32;
console.log(user.isModified('age'));
const plainObject = user.toObject();
const jsonString = JSON.stringify(user.toJSON());
await user.validate();
await user.save();
await user.remove();
🏗️ Data Storage
Your data is stored in JSON files within the specified database folder:
my-database/
├── users.json # User collection
├── posts.json # Post collection
└── comments.json # Comment collection
Each collection is a JSON array of documents:
[
{
"_id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"age": 30,
"isActive": true,
"createdAt": "2023-01-01T00:00:00.000Z",
"updatedAt": "2023-01-01T00:00:00.000Z"
}
]
🔧 Advanced Features
Custom Methods and Statics
userSchema.methods.getDisplayName = function() {
return this.name.toUpperCase();
};
userSchema.statics.findByEmail = function(email) {
return this.findOne({ email });
};
const user = await User.findOne({ name: 'John' });
console.log(user.getDisplayName());
const user = await User.findByEmail('john@example.com');
Schema Validation
const userSchema = new Schema({
email: {
type: 'String',
required: true,
validate: (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw new Error('Invalid email format');
}
return true;
}
},
age: {
type: 'Number',
required: true,
validate: (age) => {
if (age < 0 || age > 150) {
throw new Error('Age must be between 0 and 150');
}
return true;
}
}
});
📱 Module System Examples
Node.js (CommonJS)
const JsonDB = require('jdb-lite');
async function main() {
await JsonDB.connect('./database');
}
Node.js (ES Modules)
import JsonDB from 'jdb-lite';
await JsonDB.connect('./database');
TypeScript
import JsonDB, { Schema, Document } from 'jdb-lite';
interface User extends Document {
name: string;
email: string;
}
const userSchema = new Schema<User>({
name: { type: 'String', required: true },
email: { type: 'String', required: true }
});
await JsonDB.connect('./database');
const UserModel = JsonDB.model<User>('User', userSchema);
🔍 Query Examples
const users = await User.find({ age: 25 });
const user = await User.findOne({ email: 'john@example.com' });
const adults = await User.find({ age: { $gte: 18 } });
const seniors = await User.find({ age: { $gt: 65 } });
const young = await User.find({ age: { $lt: 30 } });
const newest = await User.find().sort({ createdAt: -1 }).limit(5);
const oldest = await User.find().sort({ createdAt: 1 }).limit(5);
const page2 = await User.find().skip(10).limit(10);
const totalUsers = await User.countDocuments();
const activeUsers = await User.countDocuments({ isActive: true });
🛠️ Error Handling
try {
const user = new User({
name: 'John',
age: 30
});
await user.save();
} catch (error) {
console.error('Validation error:', error.message);
}
🚀 Performance Tips
- Use indexes for frequently queried fields (planned feature)
- Limit results with
.limit() to avoid loading large datasets
- Use
.countDocuments() instead of .find().length for counting
- Close connections with
JsonDB.disconnect() when done
📚 Migration from Other Libraries
From Mongoose
const mongoose = require('mongoose');
const User = mongoose.model('User', userSchema);
const JsonDB = require('jdb-lite');
const User = JsonDB.model('User', userSchema);
From Lowdb
const low = require('lowdb');
const db = low('db.json');
const JsonDB = require('jdb-lite');
await JsonDB.connect('./database');
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
MIT License - see LICENSE file for details.
Made with ❤️ for developers who need a simple, reliable JSON database solution.