Spanish Total.js
English
Documentation For AI agents
Contents

NoSQL database

The embedded file database of Total.js 4: NOSQL() for JSON documents and TABLE() for rows with a schema, both stored in the databases/ folder and queried with the same builder.

.md GitHub
On this page

Total.js 4 has an embedded file database. NOSQL(name) stores JSON documents, TABLE(name) stores rows with a fixed set of columns. Both need no server and no installation: the data lives in plain text files in the databases/ folder of the app, and both use the same query builder.

Files and storage

CallFile
NOSQL('users')databases/users.nosql (one JSON document per line)
TABLE('users')databases/users.table (a header with the columns, then one row per line, values separated by |)

Next to the data file the engine can create users.nosql.bk with backups of changed documents (see builder.backup()). The folder comes from the directory_databases config key (/databases/ by default) and is created when it is needed.

A name that starts with ~ is an absolute path: NOSQL('~/www/data/logs.nosql'). Such an instance is not cached, so every call creates a new one. Other instances are created once and then reused.

Operations are queued and run one after another, so you can call them from anywhere without locking. Every call returns at once; the work starts in the next tick, which gives you time to add conditions to the builder.

Inserting documents

NOSQL('users').insert({ id: UID(), name: 'Peter', email: 'peter@example.com', age: 32, created: NOW }).callback(function(err, count) {
    // count: 1
});

With true as the second argument the document is inserted only when no document matches the conditions you add to the returned builder. The response is 0 when it already exists:

NOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {
    if (!count)
        console.log('The email is already registered');
});

Reading

find() returns an array, read() one document, count() an object { count: Number } and list() a page of results:

NOSQL('users').find().where('age', '>', 18).sort('name').fields('id,name,email').take(20).callback(function(err, items, meta) {
    // meta: { count, counter, scanned, duration }
});

NOSQL('users').read().id('3ab5k001pt51d').callback(function(err, user) {
    // user is the document or nothing
});

NOSQL('users').count().where('active', true).callback(function(err, response) {
    // response.count
});

read() reads the file from the end, so with several matches it returns the newest one. find2() also reads from the end and returns the newest documents first.

Conditions

All conditions are joined with AND. Field names can use dots for nested objects (address.city).

var builder = NOSQL('products').find();
builder.where('price', '>=', 10);       // =, ==, !=, <>, >, <, >=, <=
builder.where('category', 'books');     // two arguments: equality
builder.in('tags', ['new', 'sale']);    // the field (or one of its items) is in the array
builder.notin('status', ['deleted']);
builder.between('price', 10, 100);
builder.search('name', 'total');        // case-insensitive substring
builder.search('code', 'AB', 'beg');    // 'beg' = starts with, 'end' = ends with
builder.contains('photos');             // not empty
builder.empty('note');                  // empty, null or an empty array
builder.year('created', 2022);
builder.month('created', '>=', 6);
builder.or(function() {
    builder.where('stock', '>', 0);
    builder.where('preorder', true);
});
builder.callback(console.log);

rule(code, [arg]) adds a raw JavaScript condition. The code sees doc and arg:

NOSQL('users').find().rule('doc.age > arg.min && doc.roles.includes(\'admin\')', { min: 18 }).callback(console.log);

Sorting, fields and pages

sort('name') sorts ascending, sort('created_desc') descending, sort('country,name_desc') by several fields. fields('id,name') returns only these fields, fields('-password') removes a field, and fields('name as title') renames one.

take() and skip() limit the result. paginate(page, limit, [maxlimit]) takes a page number that starts at 1, which fits values from the query string. list() returns everything a grid needs:

NOSQL('users').list().where('active', true).sort('name').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {
    // response: { page, pages, limit, count, items }
});

Updating

update() (aliases modify() and mod()) changes only the fields you pass; other fields of the document stay. A prefix in the key performs an operation with the stored value:

KeyOperation
nameSet the value
+count, -count, *count, /countAdd, subtract, multiply, divide
!activeToggle a boolean (the value is ignored)
>max, <minKeep the higher / the lower value
NOSQL('products').update({ name: 'Book', '+views': 1, updated: NOW }).id(id).callback(function(err, count) {
    // count: number of changed documents
});

With true as the second argument (upsert) the data is inserted as a new document when nothing matched. builder.insert(fn) changes that document before it is written:

NOSQL('stats').update({ id: key, '+count': 1 }, true).id(key).insert(function(doc) {
    doc.created = NOW;
});

Removing and maintenance

NOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {
    console.log('Removed:', count);
});

Removed and updated documents leave unused lines in the file. clean() rewrites the file without them. clear() removes all documents, drop() deletes the data file with its backups and log.

Use in schemas

callback($) connects the builder to an operation. An error goes to $.invalid(), and the call returns a promise with the result, so it works with await. A second argument is an error used when nothing was found:

NEWSCHEMA('Users', function(schema) {

    schema.setRead(async function($) {
        var user = await NOSQL('users').read().id($.id).fields('-password').callback($, 'error-users-404');
        $.callback(user);
    });

    schema.setQuery(async function($) {
        var response = await NOSQL('users').list().autofill($, null, 'password', 'name', 50).callback($);
        $.callback(response);
    });

});

promise() returns a promise that rejects on an error, for code outside operations.

Tables

A table has a fixed schema: columns with a name and a type. Declare it in the config as table_<name>, or call alter():

table_users     : id:string(20)|name:string(50)|age:number|active:boolean|created:date
TABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');
TABLE('users').insert({ id: UID(), name: 'Anna', age: 28, active: true, created: NOW });
TABLE('users').find().where('active', true).callback(console.log);

Types are string, string(length), number, boolean (or bool), date and object. Columns can be separated with |, , or ;. Only declared columns are stored. When every column has a size (a string with a length, number, boolean, date), rows have a fixed width and updates are written in place. Changing the schema with alter() rewrites existing rows; newname=oldname:type copies values from an old column.

Performance options

textdb_inmemory in the config keeps databases smaller than the given number of megabytes in memory for reading. textdb_worker : true runs the engine in a worker thread while the web server is running.

Made in Europe