file-json-db

Quick Start

This page gets you from zero to a working database in a few minutes. We keep the examples small and focused. Larger, realistic applications are covered later in the Real-World Examples section.

1. Create a project and install

mkdir my-app && cd my-app
npm init -y
npm install file-json-db

2. Create a database

A database is just a folder on disk. Create a file app.js:

const { JSONDB } = require('file-json-db');

// Creates (or opens) the folder ./data
const db = new JSONDB('./data');

console.log('Database ready');

3. Create a collection

A collection is a place to store documents of the same kind (users, products, posts, etc.).

const users = db.collection({
  name: 'users',
  autoId: true,          // automatically generate _id
  indexes: ['email']     // fast lookup by email
});

4. Insert a document

const user = users.insert({
  name: 'Alice',
  email: 'alice@example.com',
  age: 28
});

console.log(user);
// → { name: 'Alice', email: 'alice@example.com', age: 28, _id: 1 }

The library added an _id field because we set autoId: true.

5. Find documents

// Find one document
const found = users.findOne({ email: 'alice@example.com' });
console.log(found);

// Find many documents (returns a QueryBuilder)
const adults = users.find({ age: { $gte: 18 } }).toArray();
console.log(adults);

6. Update a document

users.updateOne(
  { email: 'alice@example.com' },
  { $set: { age: 29 } }
);

console.log(users.findOne({ email: 'alice@example.com' }));
// age is now 29

7. Delete a document

users.deleteOne({ email: 'alice@example.com' });

console.log(users.findOne({ email: 'alice@example.com' }));
// → null

8. What appears on disk?

After running the script you will see:

my-app/
├── app.js
├── package.json
└── data/
    └── users/
        ├── index.json       ← metadata and indexes
        └── part-0001.json   ← the actual documents

Both files are ordinary JSON. You can open them in any text editor.

Complete minimal example

Copy this into app.js and run node app.js:

const { JSONDB } = require('file-json-db');

const db = new JSONDB('./data');

const users = db.collection({
  name: 'users',
  autoId: true,
  indexes: ['email']
});

// Insert
users.insert({ name: 'Alice', email: 'alice@example.com', age: 28 });
users.insert({ name: 'Bob',   email: 'bob@example.com',   age: 32 });

// Find
console.log('All users:', users.find({}).toArray());
console.log('Alice:', users.findOne({ email: 'alice@example.com' }));

// Update
users.updateOne(
  { email: 'alice@example.com' },
  { $set: { age: 29 }, $push: { tags: 'admin' } }
);

// Delete
users.deleteOne({ email: 'bob@example.com' });

console.log('Remaining:', users.find({}).toArray());
console.log('Collections:', db.listCollections());
Next steps