jsonbadger
v0.6.2
Published
JSONB query/model library for PostgreSQL
Maintainers
Readme
JsonBadger
JsonBadger is a Node.js library for working with complex JSON data in PostgreSQL through a schema-driven model API. Instead of building nested JSONB queries by hand, you define schemas and use document-style models, query operators, and persistence helpers.
Why did I create this utility?
I originally built my personal systems and small business client projects using MongoDB and Mongoose. Over time, that setup was no longer viable or cost-effective on shared hosting. I needed a solution that was more contained and budget-friendly. Since most shared hosting providers offer free, robust PostgreSQL databases, I created this utility to leverage PostgreSQL's jsonb fields as an alternative for document-based storage.
Table of Contents
Install
Requirements:
- Node.js >=20
- PostgreSQL
npm install jsonbadgerExamples (Quick Start)
import JsonBadger from 'jsonbadger';
// 1. Connect to database
const db_uri = 'postgresql://user:pass@localhost:5432/dbname';
const options = {
debug: false,
max: 10,
ssl: false
};
const connection = await JsonBadger.connect(db_uri, options);
// 2. Define schema (FieldType format)
const user_schema = new JsonBadger.Schema({
name: {type: String, required: true, index: true},
age: {type: Number, min: 0, index: -1},
type: {type: String},
email: {type: String, index: {unique: true, name: 'idx_users_email_unique'}}
}, {
id_strategy: JsonBadger.ID_STRATEGY.bigserial,
auto_index: true
});
// 3. Declare indexes on schema (path-level + schema-level compound index)
// Descriptor-form create_index(...) is how you define explicit index declarations.
user_schema.create_index({using: 'btree', paths: {name: 1, type: -1}});
// 4. Create model
const User = connection.model({
name: 'User',
schema: user_schema,
table_name: 'users'
});
// 5. Run migrations manually
await User.ensure_table();
await User.ensure_indexes();
// 6. Save a document
const saved_user = await User.from({
name: 'john',
age: 30,
type: 'admin'
}).save();
// returns: User document instance
// saved_user.to_json() -> { id, name, age, type, created_at, updated_at }
// 7. Find a document
const found_user = await User.find_one({
name: 'john'
}).exec();
// returns: User document instance or null
// found_user?.to_json() -> { id, name, age, type, created_at, updated_at }When using ID_STRATEGY.uuidv7, declare it on the schema. JsonBadger checks support automatically during Model.ensure_table() using capability data captured at connect(...).
Examples Cheat Sheet
For a complete copy-paste operator and runtime cheat sheet (queries, updates, and document methods), see docs/examples.md.
For the document state flow from new Model(...) through save(), hydration, dirty tracking, and serialization, see docs/lifecycle.md.
Core Features
- JSONB-first: Model API designed specifically for PostgreSQL JSONB.
- Validation: FieldType-based schema validation built in.
- Querying: Mongo-style query operators such as
$gt,$regex,$contains, and$elem_match. - Runtime document APIs:
get,set, alias virtuals, serialization helpers,mark_modified/dirty tracking, and immutable enforcement after save. - JSON updates:
update_one(...)supports implicit keys,$set,$unset, and$replace_roots. - Migrations: Helpers for
ensure_table,ensure_indexes, andensure_model. - Configurable row IDs: use
ID_STRATEGY.bigserialandID_STRATEGY.uuidv7. - ID create semantics: for
uuidv7, caller-providedidis used on create when present; otherwise PostgreSQL generates it. Forbigserial, create ignores caller-providedidand PostgreSQL generates it. - Timestamp helper semantics:
created_atandupdated_atare helper fields. Create keeps caller values when provided, otherwise auto-fills both. Updates keep callerupdated_atwhen provided, otherwise auto-refreshupdated_at. - Configurable index lifecycle:
auto_indexis a schema option that controls whetherensure_model()also ensures indexes. - UUIDv7 compatibility checks: JsonBadger checks support automatically and fails early when unavailable.
- Document instance returns: data-returning methods return document instances with top-level base fields (
id,created_at,updated_at), and.to_json()/.$serialize()for plain-object snapshots. - Modern: Native ESM package.
Documentation
docs/api/index.mddocs/api/model.md(model construction, queries, persistence, and document methods)docs/api/schema.mddocs/api/query-builder.mddocs/api/connection.md(connection API, lifecycle, and shared-connection examples)docs/api/field-types.mddocs/examples.md(complete example cheat sheet for queries, updates, and runtime document methods)docs/lifecycle.md(document phases, hydration/save flow, dirty tracking, and serialization)docs/advanced/query-translation.md(advanced PostgreSQL reference for operators and query behavior)docs/local-integration-testing.mdCHANGELOG.mdfor release notes and version history
Author
Carlos López
- GitHub: @carlosjln
License
MIT. See LICENSE.
