Menu
#Node and Bun
ferrite-db is a TypeScript client and set of typed models for ferrite_db. It runs on Node 20 or newer and on Bun, has no runtime dependencies, and takes the types of your documents, filters, updates and projections from the schema you write. It speaks the JSON-lines protocol over node:net and node:tls, with SCRAM-SHA-256 and token login, a small connection pool and pipelining.
The package is version 0.5.0. Expect rough edges.
npm i ferrite-db
# or
bun add ferrite-dbIt ships ESM and CommonJS builds with type declarations. There is no browser build, since the client needs TCP sockets. You also need a server, see getting started and deployment.
#Quick start
import { connect, model, t, type Infer } from "ferrite-db";
const User = model("users", {
name: t.string().trim(),
email: t.string().lowercase().unique(),
age: t.int().optional(),
score: t.float().default(0),
tags: t.array(t.string()),
createdAt: t.date().default(() => new Date()),
});
type User = Infer<typeof User>;
const client = await connect("ferrite://127.0.0.1:7878/shop");
await User.create({ name: " Ada ", email: "[email protected]", age: 36, tags: ["admin"] });
const adults: User[] = await User.find({ age: { $gt: 18 } }).sort({ name: 1 }).limit(10);
await User.updateOne({ email: "[email protected]" }, { $inc: { score: 1.5 }, $push: { tags: "founder" } });
await client.close();connect() opens the connection and, for the first client, makes it the one models use. Using a model before connect() throws NotConnectedError straight away instead of waiting.
#Connecting
The string is described in connection strings. Options can also be passed as an object, which wins over the string:
const client = await connect("ferrite://127.0.0.1/shop", { poolSize: 8, timeout: 5000 });| option | default | meaning |
|---|---|---|
poolSize |
4 |
connections in the pool, opened when needed (1 to 256) |
pipeline |
8 |
requests on the wire at once on one connection (1 to 1024) |
connectTimeout |
10000 |
ms to open a connection. 0 is no limit |
timeout |
30000 |
ms for one request. 0 is no limit. A request that runs out fails alone with TimeoutError |
keepAlive |
10000 |
TCP keepalive start, in ms. 0 is off |
idleTimeout |
30000 |
ms before an unused connection is closed |
format |
json |
json or binary |
connect() checks the server and the login before it returns. A wrong login fails with AuthenticationError. A lost connection is replaced on the next request, and the request that was in flight fails with ConnectionLostError. It is not retried, since a write may have gone through. connect() does not retry either.
timeout can be set per model, per collection, or per call with withTimeout(ms):
await User.withTimeout(500).find({ age: { $gt: 18 } });
await Report.withTimeout(0).aggregate(pipeline); // no limit#The first user
The token logs in as an admin. Use it to make the first user, who has to be an admin on *:
const root = await connect("ferrite://127.0.0.1", { token: process.env.FERRITE_TOKEN });
await root.createUser({ user: "boss", password: "a long password", role: "admin" });
await root.createUser({ user: "shop", password: "another long one", grants: [{ db: "shop", role: "readWrite" }] });
await root.close();
const client = await connect("ferrite://shop:another%20long%[email protected]/shop");createUser sends the password, so use tls=true. See authentication.
#Schemas
model(name, shape) makes a schema from an object of t fields and adds _id (an ObjectId).
t.string() // .min .max .length .regex .trim .lowercase .uppercase
t.int() // .min .max. A safe integer, stored as an Int
t.float() // .min .max. Stored as a Float
t.bigint() // an Int beyond 2^53, as a bigint
t.boolean()
t.date()
t.objectId()
t.array(t.string())
t.object({ city: t.string() })
t.enum(["admin", "member"])
t.literal("v1")
t.union([t.string(), t.int()])
t.any()Modifiers: .optional(), .nullable(), .default(value or function), .unique(), .index(), .validate(fn, message), .hidden(), .ref(Model).
create() and replaceOne() check the input, apply trim and friends, fill defaults, and refuse unknown fields. Every problem is collected into a ValidationError with issues, and nothing is sent if there is one. Reads are not validated: the server is the source of truth. schema(shape).parse(body) checks any value and can be used as a request-body validator.
Int and float are different types, as in the database: t.int() writes an Int and rejects 1.5, and t.float() writes a Float even for 1.
#Queries
const page = await User.find({ age: { $gte: 18 }, "address.city": "Leeds" })
.sort({ age: -1, name: 1 })
.skip(20)
.limit(10);
await User.findOne({ email: "[email protected]" });
await User.findById(id);
await User.count({ age: { $gt: 18 } });
await User.exists({ email: "[email protected]" });
await User.distinct("tags");find() returns a query that is sent when awaited. Filters are checked against the schema: field names, dotted paths, the operators each type allows, and the type of each value. { agee: 1 } is a compile error. A filter that holds undefined is refused. See filters.
select() keeps or leaves out fields, and the result type follows:
const names = await User.find({}).select({ name: 1, age: 1 });#Updates
await User.updateOne({ email: "[email protected]" }, { $set: { name: "Ada L" }, $inc: { score: 1 } });
await User.updateMany({}, { $addToSet: { tags: "member" } });
await User.replaceOne({ email: "[email protected]" }, { name: "Ada", email: "[email protected]", tags: [] });
await User.deleteOne({ email: "[email protected]" });
await User.deleteMany({ age: { $lt: 18 } }); // the filter is required
await User.updateOne(filter, update, { upsert: true });
const before = await User.findOneAndUpdate(filter, update, { returnDocument: "after" });Updates are checked against the schema too. $inc keeps the .min() and .max() of a field by adding a bound to the filter, so a call that would leave the range matches nothing. updateOne and updateMany return { count, upsertedId? }, and deletes return { deleted }. See updates.
#Populate
const Post = model("posts", {
title: t.string(),
author: t.objectId().ref(User),
tags: t.array(t.objectId().ref(Tag)),
});
const posts = await Post.find().populate("author", "tags");
await Post.find().populate("author", { select: ["name", "email"] });
await Post.find().populate("author.org"); // nestedPopulate is done on the client, with one extra find with $in for each populated path, and the join in memory. A missing document gives null. Without select a populated document has every field of the other model, so use select or .hidden() where you send it out.
#Hooks, timestamps, computed fields
const User = model("users", { email: t.string(), password: t.string() }, {
timestamps: true,
hooks: {
beforeCreate: async (doc) => ({ ...doc, password: await hash(doc.password) }),
afterDelete: (result, filter) => audit(result.deleted, filter),
},
computed: { domain: (u) => u.email.split("@")[1] },
});timestamps: trueaddscreatedAtandupdatedAt, using the clock of the calling process. Other names, or one left out, go in an object:{ createdAt: "created", updatedAt: false }.- Hooks are
beforeCreate,afterCreate,beforeUpdate,afterUpdate,beforeReplace,afterReplace,beforeDelete,afterDelete. Abeforehook that throws cancels the call. Anafterhook that throws rejects the call, but the write is done. They run only for calls through the model, not forUser.collectionor anything on the server. - Computed fields are plain functions of the stored document, worked out on every read and never stored.
.hidden()on a top-level field keeps it out of what the model reads.
#Indexes
.unique(), .index() and schema(...).index({ room: 1, day: 1 }, { unique: true }) declare indexes. Nothing builds one on its own. Call await User.syncIndexes() from a setup script or at startup. syncIndexes({ dryRun: true }) shows the plan, and { drop: true } drops indexes the schema does not declare. A unique index only protects you after syncIndexes() has run. See indexes.
#Aggregate
const rows = await Order.aggregate<{ _id: string; total: number }>([
{ $match: { status: "paid" } },
{ $group: { _id: "$customer", total: { $sum: "$amount" } } },
]);The first stages are checked against the schema. After a reshaping stage the rows come back as plain objects typed by the type argument. See aggregation.
#The untyped client
ferrite-db/client has the client alone, with no schemas. client.db().collection("users") gives a collection of loose objects with insertOne, insertMany, find, findOne, get, count, updateOne, updateMany, replaceOne, deleteOne, deleteMany, findOneAndUpdate, findOneAndDelete, distinct, aggregate, createIndex, dropIndex, listIndexes and drop. The client has listDatabases(), the user commands, and command() for any raw request.
Numbers are what you give it: a plain 1 is an Int, and a float is written float(1).
import { connect, float } from "ferrite-db/client";
const users = (await connect("ferrite://127.0.0.1/shop")).db().collection("users");
await users.insertOne({ name: "Ada", score: float(0) });#Two databases
model.bind(db) gives the same model on another database, which is also how to use models in tests:
const client = await connect("ferrite://127.0.0.1");
const staging = Event.bind(client.db("staging"));#Errors
Every error is a FerriteError with a string code: ValidationError, DuplicateKeyError, UnauthorizedError, AuthenticationError, BadRequestError, InvalidError, LimitError, StorageError, NotConnectedError, ConfigError, ConnectionError, ConnectionLostError, TlsError, TimeoutError and ProtocolError. The server's own codes are in errors.
#Not in 0.5.0
- Transactions and change streams. The package has no helpers for
begin,commitorwatch, and its README lists change streams as not done. Requests are spread over a pool, so a transaction (which lives on one connection) is not something to build onclient.command(). See transactions and change streams. - No plugins.
- A lost connection fails the requests in flight and is not retried.
- Stages of an aggregate after the first reshaping one are not typed.
Infergivesnumberfor both int and float fields.