Example: A Mini Shop (simplified flow)

A single-file, end-to-end example: users, items, prices, store inventory, and a balance-checked/item-availability order flow running inside an ACID transaction.

Setup

Before the client code below can connect, create a server user and grant it access to the database this example uses:

sudo diana-db add-user -u admin -p password
sudo diana-db grant-access -u admin -db data:3
          

Install

npm i @diana-db/odm
          

1. Connect

const DATABASE = 'data';

const dianaDb = new DianaDb({
  host: process.env.DIANA_DB_HOST || 'localhost',
  port: Number(process.env.DIANA_DB_PORT || 34567),
  user: process.env.DIANA_DB_USER || 'admin',
  password: process.env.DIANA_DB_PASSWORD || 'password',
  connectionPoolSize: 3,
  connectTimeoutValue: 1000,
});
          

2. Random data helpers

function rndInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Random amount with 2 decimal places, inclusive of min/max.
function rndAmount(min, max) {
  return Math.round((Math.random() * (max - min) + min) * 100) / 100;
}

// Pick `count` distinct random elements from an array.
function rndSample(arr, count) {
  const n = Math.min(count, arr.length);
  const shuffled = [...arr].sort(() => Math.random() - 0.5);
  return shuffled.slice(0, n);
}

// Pick one random element from an array.
function rndPick(arr) {
  return arr[rndInt(0, arr.length - 1)];
}

function rndSex() {
  return Math.random() < 0.5 ? 'm' : 'f';
}

// A plausible date of birth for an 18-75 year old, as an ISO date string.
function rndDob() {
  const msPerYear = 365.25 * 24 * 60 * 60 * 1000;
  const minAgeMs = 18 * msPerYear;
  const maxAgeMs = 75 * msPerYear;
  const ts = Date.now() - (minAgeMs + Math.random() * (maxAgeMs - minAgeMs));
  return new Date(ts).toISOString().slice(0, 10);
}

function rndTags() {
  const pool = ['new', 'vip', 'wholesale', 'trial', 'referred', 'newsletter'];
  return rndSample(pool, rndInt(0, 3));
}

const FIRST_NAMES = [
  'James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer', 'Michael', 'Linda',
  'William', 'Elizabeth', 'David', 'Barbara', 'Richard', 'Susan', 'Joseph', 'Jessica',
  'Thomas', 'Sarah', 'Charles', 'Karen', 'Somchai', 'Malee', 'Anong', 'Chai',
];

const LAST_NAMES = [
  'Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis',
  'Rodriguez', 'Martinez', 'Wilson', 'Anderson', 'Taylor', 'Moore', 'Jackson', 'Martin',
  'Saetang', 'Charoen', 'Suksawat', 'Wongsawat',
];

const EMAIL_DOMAINS = ['example.com', 'mail-test.dev', 'demo-inbox.io'];

function rndFullName() {
  return { firstname: rndPick(FIRST_NAMES), lastname: rndPick(LAST_NAMES) };
}

// A plausible-looking, not-necessarily-unique email built from a name plus
// a random suffix and a fixed pool of throwaway domains.
function rndEmail(firstname, lastname) {
  const domain = rndPick(EMAIL_DOMAINS);
  return `${firstname}.${lastname}${rndInt(1, 9999)}@${domain}`.toLowerCase();
}

function rndUser() {
  const { firstname, lastname } = rndFullName();
  return {
    email: rndEmail(firstname, lastname),
    firstname,
    lastname,
    dob: rndDob(),
    sex: rndSex(),
    tags: rndTags(),
  };
}

// A coordinate within `radiusKm` of an origin point, so demo users cluster
// around a real city instead of landing at random points on the globe.
// Samples uniformly over the disc (sqrt of a random distance, not a random
// distance directly) and offsets by a random bearing.

function rndPosition() {
  const originLat = 13.7563;
  const originLng = 100.5018;
  const radiusKm = 50;
  const earthRadiusKm = 6371;

  const distanceKm = radiusKm * Math.sqrt(Math.random());
  const bearing = Math.random() * 2 * Math.PI;
  const latRad = (originLat * Math.PI) / 180;

  const deltaLat = (distanceKm / earthRadiusKm) * Math.cos(bearing);
  const deltaLng = (distanceKm / (earthRadiusKm * Math.cos(latRad))) * Math.sin(bearing);

  const lat = originLat + (deltaLat * 180) / Math.PI;
  const lng = originLng + (deltaLng * 180) / Math.PI;

  return { x: lng, y: lat };
}

const PRODUCT_ADJECTIVES = [
  'Ergonomic', 'Rustic', 'Sleek', 'Handcrafted', 'Durable', 'Compact',
  'Premium', 'Lightweight', 'Vintage', 'Modern', 'Portable', 'Refined',
];

const PRODUCT_NOUNS = [
  'Chair', 'Lamp', 'Backpack', 'Keyboard', 'Mug', 'Jacket',
  'Shelf', 'Speaker', 'Wallet', 'Notebook', 'Bottle', 'Sofa',
];

// Plausible-sounding, not-necessarily-unique catalog copy from two small
// word pools instead of a generator library.
function rndItem() {
  const adjective = rndPick(PRODUCT_ADJECTIVES);
  const noun = rndPick(PRODUCT_NOUNS);
  return {
    title: `${adjective} ${noun}`,
    description: `A ${adjective.toLowerCase()} ${noun.toLowerCase()} built to last.`,
  };
}

function rndSerialNumber(existing) {
  let candidate = rndInt(100000, 999999);
  while (existing.has(candidate)) {
    candidate = rndInt(100000, 999999);
  }
  existing.add(candidate);
  return candidate;
}
          

3. Define every schema and model

Seven collections make up the shop. Each one pairs a plain schema object with a Model instance — see Schema and Types for the full field option reference. None of these are initialized yet; that happens all together in initModels(), the next step.

User

The account itself.

const userSchema = {
  email: {
    type: Types.STRING,
    required: true,
    unique: true,
    lowercase: true,
  },
  firstname: {
    type: Types.STRING,
    required: true,
  },
  lastname: {
    type: Types.STRING,
    required: true,
  },
  dob: {
    type: Types.TIME,
    required: true,
  },
  sex: {
    type: Types.STRING,
  },
  created: {
    type: Types.TIME,
    required: true,
    default: () => new Date().toISOString(),
  },
  active: {
    type: Types.BOOLEAN,
    default: true,
  },
  tags: {
    type: Types.ARRAY,
    items: Types.STRING,
    default: () => [],
  },
};

const userModel = new Model({
  database: DATABASE,
  collection: 'user',
  name: 'User',
  schema: userSchema,
});
          

UserLocation

const userLocationSchema = {
  user: {
    type: Types.REFERENCE,
    reference: 'user',
    required: true,
    triggerRemove: true,
  },
  location: {
    type: Types.POSITION,
    required: true,
  },
};

const userLocationModel = new Model({
  database: DATABASE,
  collection: 'userLocation',
  name: 'UserLocation',
  schema: userLocationSchema,
});
          

Item

The catalog entry — a title and description, with no price or stock of its own.

const itemSchema = {
  title: {
    type: Types.STRING,
    required: true,
  },
  description: {
    type: Types.STRING,
    required: true,
  },
  created: {
    type: Types.TIME,
    required: true,
    default: () => new Date().toISOString(),
  },
};

const itemModel = new Model({
  database: DATABASE,
  collection: 'item',
  name: 'Item',
  schema: itemSchema,
});
          

Price

Prices are append-only: every price change inserts a new Price document rather than updating an existing one, which is what lets the currentPrice view (created in the next step) reconstruct "the latest price" by sorting on created. The read helper for that view lives right here, next to the model:

const priceSchema = {
  item: {
    type: Types.REFERENCE,
    reference: 'item',
    required: true,
    triggerRemove: true,
  },
  amount: {
    type: Types.NUMBER,
    required: true,
    precision: 2,
  },
  currency: {
    type: Types.STRING,
    required: true,
    default: 'USD',
  },
  created: {
    type: Types.TIME,
    required: true,
    default: () => new Date().toISOString(),
  },
};

const priceModel = new Model({
  database: DATABASE,
  collection: 'price',
  name: 'Price',
  schema: priceSchema,
});

async function getCurrentPrice(itemId) {
  const [row] = await priceModel.findByView('currentPrice', { item: { $eq: itemId } });
  return row?.price;
}
          

StoreItem

One document per physical unit in stock, each with its own serialNumber. An Item can have many StoreItem units. reserved tracks whether a unit is already tied to an order — it starts false and flips to true the moment an order is placed for it, so it stops counting as available stock in the inventory view. reservedFor records which user holds that reservation. Here default is given as a factory function (() => false) rather than a bare value — both forms are valid, the same way tags on User uses () => [].

const storeItemSchema = {
  item: {
    type: Types.REFERENCE,
    reference: 'item',
    required: true,
    triggerRemove: true,
  },
  serialNumber: {
    type: Types.NUMBER,
    required: true,
    precision: 0,
  },
  reserved: {
    type: Types.BOOLEAN,
    default: () => false,
  },
  reservedFor: {
    type: Types.REFERENCE,
    reference: 'user',
  },
  created: {
    type: Types.TIME,
    required: true,
    default: () => new Date().toISOString(),
  },
};

const storeItemModel = new Model({
  database: DATABASE,
  collection: 'storeItem',
  name: 'StoreItem',
  schema: storeItemSchema,
});

async function getAvailableCount(itemId) {
  const [row] = await storeItemModel.findByView('inventory', { item: { $eq: itemId } });
  return row?.count ?? 0;
}
          

Transaction

Every movement of money — deposits, withdrawals, and order payments — is one Transaction document. A positive amount is money coming in, a negative one is money going out; status starts as 'pending' and moves to 'succeeded' once settled.

const transactionSchema = {
  user: {
    type: Types.REFERENCE,
    reference: 'user',
    required: true,
    triggerRemove: true,
  },
  amount: {
    type: Types.NUMBER,
    required: true,
    precision: 2,
  },
  currency: {
    type: Types.STRING,
    default: 'USD',
  },
  created: {
    type: Types.TIME,
    default: () => new Date().toISOString(),
  },
  status: {
    type: Types.STRING,
    required: true,
    default: 'pending',
  },
};

const transactionModel = new Model({
  database: DATABASE,
  collection: 'transaction',
  name: 'Transaction',
  schema: transactionSchema,
});

async function getUserBalance(userId) {
  const [deposits] = await transactionModel.findByView('balancePendingDeposits', { user: { $eq: userId } });
  const [withdrawals] = await transactionModel.findByView('balancePendingWithdrawals', { user: { $eq: userId } });
  const [actual] = await transactionModel.findByView('balanceActual', { user: { $eq: userId } });
  return {
    user: userId,
    amount: {
      pending_deposits: deposits?.pending_deposits ?? 0,
      pending_withdrawals: withdrawals?.pending_withdrawals ?? 0,
      actual: actual?.actual ?? 0,
    },
  };
}
          

Order

References the specific StoreItem units purchased (not the Item catalog entries), so each order is tied to the exact physical units that left the shelf. status tracks where the order sits in its lifecycle: 'toPay' (items are reserved but not yet paid for), 'toShip' (paid, waiting to go out), or 'toReview' (delivered, waiting on the buyer) — this example only ever inserts an order as 'toPay' or 'toShip'. amount/currency capture the order's total at creation time (the sum of its items' current prices), so the price the buyer agreed to doesn't drift if prices change later.

const orderSchema = {
  items: {
    type: Types.ARRAY,
    items: Types.REFERENCE,
    reference: 'storeItem',
    required: true,
  },
  user: {
    type: Types.REFERENCE,
    reference: 'user',
    required: true,
    triggerRemove: true,
  },
  status: {
    type: Types.STRING,
    required: true,
    default: 'toPay',
  },
  amount: {
    type: Types.NUMBER,
    required: true,
    precision: 2,
  },
  currency: {
    type: Types.STRING,
    required: true,
    default: 'USD',
  },
  created: {
    type: Types.TIME,
    required: true,
    default: () => new Date().toISOString(),
  },
};

const orderModel = new Model({
  database: DATABASE,
  collection: 'order',
  name: 'Order',
  schema: orderSchema,
});
          

4. Initialize every model and create its views

initModels() is where everything declared above actually gets registered with the server: it opens the connection, calls .init() on all seven models, and then creates every materialized view. It's called once, at the very start of main(), before dispatching to either the init or flow mode below.

async function initModels() {
  await dianaDb.connect(1000);
  await userModel.init();
  await userLocationModel.init();
  await itemModel.init();
  await priceModel.init();
  await storeItemModel.init();
  await transactionModel.init();
  await orderModel.init();

  await priceModel.createView('currentPrice', [
    { $sort: { created: 1 } },
    {
      $group: {
        _id: '$item',
        item: { $first: '$item' },
        price: { $last: '$amount' },
      },
    },
  ]);

  // Available stock per item: { item, count }, filtered down to unreserved
  // units only, so a unit tied up in someone else's order doesn't count
  // toward what's available to buy. reserved: { $ne: true } matches both
  // reserved: false and a missing/undefined reserved field.
  await storeItemModel.createView('inventory', [
    { $match: { reserved: { $ne: true } } },
    {
      $group: {
        _id: '$item',
        item: { $first: '$item' },
        count: { $sum: [1] },
      },
    },
  ]);

  await transactionModel.createView('balancePendingDeposits', [
    { $match: { status: { $eq: 'pending' }, amount: { $gt: 0 } } },
    { $group: { _id: '$user', user: { $first: '$user' }, pending_deposits: { $sum: ['$amount'] } } },
  ]);

  await transactionModel.createView('balancePendingWithdrawals', [
    { $match: { status: { $eq: 'pending' }, amount: { $lt: 0 } } },
    { $group: { _id: '$user', user: { $first: '$user' }, pending_withdrawals: { $sum: ['$amount'] } } },
  ]);

  await transactionModel.createView('balanceActual', [
    { $match: { status: { $eq: 'succeeded' } } },
    { $group: { _id: '$user', user: { $first: '$user' }, actual: { $sum: ['$amount'] } } },
  ]);

  await orderModel.createView('orderToPay', [
    { $match: { status: { $eq: 'toPay' } } },
    // order.user and userLocation.user both hold the same user _id, so this
    // join doesn't need the user lookup to run first
    { $lookup: { database: DATABASE, collection: 'userLocation', localField: 'user', foreignField: 'user', as: 'location' } },
    { $unwind: '$location' },
    { $lookup: { database: DATABASE, collection: 'user', localField: 'user', foreignField: '_id', as: 'user' } },
    { $unwind: '$user' },
    { $project: { _id: false, location: '$location', user: true, items: true, amount: true, currency: true } },
  ]);

  await orderModel.createView('orderToShip', [
    { $match: { status: { $eq: 'toShip' } } },
    // NOTE: this must look up the `userLocation` collection, same as
    // orderToPay above -- there is no `location` collection.
    { $lookup: { database: DATABASE, collection: 'userLocation', localField: 'user', foreignField: 'user', as: 'location' } },
    { $unwind: '$location' },
    { $lookup: { database: DATABASE, collection: 'user', localField: 'user', foreignField: '_id', as: 'user' } },
    { $unwind: '$user' },
    { $project: { _id: false, location: '$location', user: true, items: true, amount: true, currency: true } },
  ]);
}
          

Querying orderToShip by location

Because the coordinate lives at location.location on an orderToShip row, querying it spatially means matching on that nested path rather than on location directly. $nearLines matches documents within a given distance of one or more line segments — useful for something like "which orders waiting to ship sit along today's delivery route":

const shipmentsAlongRoute = await orderModel.findByView('orderToShip', {
  'location.location': {
    $nearLines: {
      lines: [
        [{ x: 1, y: 1 }, { x: 10, y: 10 }],
        [{ x: 2, y: 0 }, { x: 4, y: 20 }],
      ],
      distance: 10,
    },
  },
});
          

5. Create users and their locations

const USER_COUNT = 10;

async function seedUsers() {
  const users = [];
  for (let i = 0; i < USER_COUNT; i++) {
    const user = await userModel.insert(rndUser());
    users.push(user);
    await userLocationModel.insert({ user: user._id, location: rndPosition() });
  }
  return users;
}
          

6. Create items and their first prices

const ITEM_COUNT = 10;

async function seedItems() {
  const items = [];
  for (let i = 0; i < ITEM_COUNT; i++) {
    const item = await itemModel.insert(rndItem());
    items.push(item);
    await priceModel.insert({
      item: item._id,
      amount: rndAmount(10, 100),
      currency: 'USD',
    });
  }
  return items;
}
          

7. Add store items (stock)

Give each item 1–5 physical units, each with its own unique serialNumber. reserved is passed explicitly as false here (its schema default would apply either way):

async function seedStoreItems(items) {
  for (const item of items) {
    const usedSerials = new Set();
    const unitCount = rndInt(1, 5);
    for (let i = 0; i < unitCount; i++) {
      await storeItemModel.insert({
        item: item._id,
        serialNumber: rndSerialNumber(usedSerials),
        reserved: false,
      });
    }
  }
}
          

8. Add money to users (deposits)

A deposit is just a Transaction with a positive amount and status: 'succeeded'. This is what the balanceActual view sums up per user to produce a spendable balance:

async function seedDeposits(users) {
  for (const user of users) {
    await transactionModel.insert({
      user: user._id,
      amount: rndAmount(10, 100),
      currency: 'USD',
      status: 'succeeded',
    });
  }
}

async function runInit() {
  const users = await seedUsers();
  const items = await seedItems();
  await seedStoreItems(items);
  await seedDeposits(users);
}
          

9. Create orders

The following runs once per user (for example inside a processOrder(user, items) step called in a loop). Creating an order checks two things, not just one: does the user have enough money, and is there actually stock left to sell. Start with availability — for each candidate item, ask the inventory view whether any unreserved units exist, then pull the actual list of available StoreItem documents for the ones that do:

async function pickAvailableStoreItems(candidateItems) {
  const chosen = [];

  for (const item of candidateItems) {
    // Availability check #1: does the inventory view show any unreserved stock at all?
    const [inventory] = await storeItemModel.findByView('inventory', { item: { $eq: item._id } });
    if (!inventory || inventory.count < 1) continue;

    // Pull the actual list of unreserved units for this item -- the view only
    // gives a count, not which units are free
    const [storeItem] = await storeItemModel.find(
      [{ item: { $eq: item._id }, reserved: { $ne: true } }],
      undefined, undefined, 0, 1,
    );
    if (storeItem) chosen.push(storeItem);
  }

  return chosen;
}

async function orderTotal(storeItems) {
  let total = 0;
  for (const storeItem of storeItems) {
    const price = await getCurrentPrice(storeItem.item);
    total += price ?? 0;
  }
  return Math.round(total * 100) / 100;
}

const candidateItems = rndSample(items, rndInt(1, 5));
const chosen = await pickAvailableStoreItems(candidateItems);
if (chosen.length === 0) return; // nothing available right now, try the next user

const total = await orderTotal(chosen);
          

Then open a transaction scoped to the shared database and reserve the chosen units before the order references them: the update's filter requires reserved: { $ne: true }, so a unit another order grabbed a moment earlier won't match. A follow-up read confirms every unit really did flip to reserved: true for this user — and this is the only condition that rolls the transaction back. Money is handled differently: if the balance covers the total, a debiting Transaction is inserted and the order goes out as 'toShip', carrying its amount/currency; if it doesn't, the order is still created — as 'toPay', with the same amount/currency and its items still reserved — and simply waits to be paid later:

const transactionId = await dianaDb.startTransaction({
  database: DATABASE,
  autoRollBackAfterMs: 60000,
});
const txnParams = { database: DATABASE, transactionId };

try {
  // Reserve first. The reserved: { $ne: true } filter means this only
  // matches units nobody else has claimed since we read them above.
  await storeItemModel.update(
    [{ _id: { $in: chosen.map((si) => si._id) }, reserved: { $ne: true } }],
    { reserved: true, reservedFor: user._id },
    transactionId,
  );

  // Availability check #2: confirm the reservation actually stuck for every
  // chosen unit. If a concurrent order beat us to one of them, it will still
  // show reserved: false (or reservedFor someone else) and be missing here.
  // This is the only condition that rolls the transaction back.
  const confirmedReserved = await storeItemModel.find(
    [{ _id: { $in: chosen.map((si) => si._id) }, reserved: { $eq: true }, reservedFor: { $eq: user._id } }],
    undefined, undefined, 0, chosen.length,
    transactionId,
  );

  if (confirmedReserved.length !== chosen.length) {
    await dianaDb.rollbackTransaction(txnParams);
    return;
  }

  const balance = await getUserBalance(user._id);
  const orderItems = confirmedReserved.map((si) => si._id);

  if (balance.amount.actual >= total) {
    // Enough money: charge now, ship now. The items stay reserved --
    // they're now owned by this order rather than up for grabs again.
    await transactionModel.insert(
      {
        user: user._id,
        amount: -total,
        currency: 'USD',
        status: 'succeeded',
      },
      transactionId,
    );
    await orderModel.insert(
      { items: orderItems, user: user._id, status: 'toShip', amount: total, currency: 'USD' },
      transactionId,
    );
  } else {
    // Not enough money yet: no transaction is created, but the order still
    // exists -- toPay -- holding the reservation until it's settled.
    await orderModel.insert(
      { items: orderItems, user: user._id, status: 'toPay', amount: total, currency: 'USD' },
      transactionId,
    );
  }

  await dianaDb.commitTransaction(txnParams);
} catch (err) {
  await dianaDb.rollbackTransaction(txnParams);
}
          

Recap

StepWhat it doesRelated reference
SetupCreate a server user and grant it database accessInstall and Run DianaDb Server
ConnectConstruct the shared DianaDb instance (connection happens in initModels())Overview
Random helpersGenerate realistic demo names, emails, birthdates, coordinates, and product copy — no external package—
Schemas & modelsDefine all seven collections and their fields, plus each view's read helperSchema and Types
Initialize & viewsConnect, call .init() on every model, then create every materialized viewMaterialized Views
UsersInsert users and their locationsInsert Documents
ItemsInsert catalog items and their first pricesInsert Documents
Store itemsAdd physical stock units with unique serial numbers, unreserved by defaultInsert Documents
DepositsAdd money to a user's balance via a succeeded transactionInsert Documents
OrdersCheck inventory availability, reserve the chosen store items, then create the order as toShip if the balance covers it or toPay if it doesn't — only insufficient inventory rolls backTransactions