@tomhundley/prismdb
v1.0.0
Published
Embedded document database for Node.js with Mongo-style queries, indexes, aggregations, transactions, and JSON persistence
Maintainers
Readme
@tomhundley/prismdb
An embedded document database for Node.js. Store JSON documents in collections, query them with Mongo-style operators, index fields, run aggregations, wrap writes in transactions, and persist to a JSON file.
Zero runtime dependencies. Node 18+.
Install
npm install @tomhundley/prismdbQuick start
import { createDb } from "@tomhundley/prismdb";
const db = createDb({ name: "shop" });
const users = db.collection("users");
users.insertOne({ name: "Ada", age: 36, tags: ["math", "cs"] });
users.insertMany([
{ name: "Grace", age: 85, tags: ["navy"] },
{ name: "Alan", age: 41, tags: ["crypto"] },
]);
const found = users
.find({ age: { $gte: 36 } })
.sort({ name: 1 })
.project({ name: 1, age: 1 })
.toArray();Queries
users.find({ name: "Ada" });
users.find({ age: { $gt: 30, $lt: 50 } });
users.find({ tags: { $in: ["math"] } });
users.find({ $or: [{ name: "Ada" }, { age: { $gte: 80 } }] });
users.find({ name: { $regex: "^A", $options: "i" } });
users.find({ $text: { $search: "crypto" } });Operators: $eq $ne $gt $gte $lt $lte $in $nin $exists $regex $size $type $all $elemMatch $not $mod $and $or $nor $text.
Updates: $set $unset $inc $mul $min $max $push $pull $addToSet $rename $currentDate.
Indexes, schema, aggregation
users.createIndex("email", { unique: true, name: "email_unique" });
const orders = db.collection("orders");
orders.insertMany([
{ sku: "book", qty: 2, price: 10 },
{ sku: "book", qty: 1, price: 10 },
{ sku: "pen", qty: 5, price: 2 },
]);
const totals = orders.aggregate([
{ $unwind: "$qty" },
{ $group: { _id: "$sku", sold: { $sum: "$qty" }, avg: { $avg: "$price" } } },
{ $sort: { sold: -1 } },
]);Schema on create:
const db = createDb({
schemas: {
users: {
name: { type: "string", required: true },
age: { type: "number", min: 0 },
role: { type: "string", enum: ["admin", "user"] },
},
},
});Transactions and persistence
db.transaction((tx) => {
tx.collection("accounts").updateOne({ name: "Ada" }, { $inc: { balance: -20 } });
tx.collection("accounts").updateOne({ name: "Grace" }, { $inc: { balance: 20 } });
});
import { saveToFile, loadFromFile } from "@tomhundley/prismdb";
await saveToFile(db, "./data/shop.json");
const restored = await loadFromFile("./data/shop.json");If the transaction function throws, all collections roll back to the snapshot taken at the start.
Change feed
users.watch(({ type, documents }) => {
console.log(type, documents.map((d) => d._id));
});What it is for
Use PrismDB when you want a small local database inside a Node process: CLIs, tests, desktop tools, caches, prototypes — without running MongoDB or SQLite. It is not a networked server and not a replacement for Postgres at scale.
License
MIT
