Spanish Total.js
English
Documentation For AI agents
Contents

NoSQL database

The embedded NoSQL database: NOSQL(name), files in databases/, inserting, finding, updating and removing documents with the query builder.

.md GitHub
On this page

Total.js 5 includes a small embedded NoSQL database. It needs no server and no driver: each database is a text file in the databases/ directory with one JSON document per line. It is a good fit for settings, logs, small catalogs and prototypes.

NOSQL('users').insert({ id: UID(), name: 'Peter', age: 33, dtcreated: NOW }).callback(function(err, response) {
    // response === 1
});

NOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {
    // response is an array of documents
});

NOSQL(name) returns a small object with the methods insert(), find(), read(), update() (alias modify()), remove(), clear() and clean(). Each of them returns a query builder where you add filters and options and then read the result with .callback() or .promise(). The full list is in the reference NoSQL database.

Files in databases/

NOSQL('users') uses the file databases/users.nosql in the root of the application. The directory and the file are created when they are needed, so you do not have to prepare anything. Use the configuration key $dirdatabases to move the directory somewhere else.

A name that contains a slash is used as a file path as it is, without the .nosql extension:

NOSQL('/data/shared/orders.nosql').find().callback(console.log);

The file is plain text. Every insert appends a new line with the JSON document. A removed document stays in the file and its line is marked with - at the beginning; such lines are skipped by every read. An update that keeps the same length rewrites the line in place; otherwise the old line is marked as removed and the new version is appended at the end. Call clean() from time to time to drop the marked lines and make the file smaller.

All operations on one file go through a queue: writes (insert, update, remove) run one after another and never at the same time as clear() or clean(); up to three reads can run at the same time.

Inserting

insert(doc) appends the document. NoSQL does not generate any identifier, so add your own id (for example with UID()). The response is 1.

NOSQL('products').insert({ id: UID(), name: 'Keyboard', price: 49.9, tags: ['usb', 'black'], dtcreated: NOW }).callback(function(err, response) {
    console.log('inserted', response);
});

Dates are stored as ISO strings and every read converts them back to Date objects, so you can compare them and sort by them.

Finding documents

find() returns all documents that match the filter as an array (an empty array when nothing matches). read() returns one document, or undefined when nothing matches.

Without sort(), documents come from the end of the file: the most recently written first. Add sort() when the order matters.

NOSQL('products').find().where('price', '<', 100).in('tags', ['usb']).fields('id,name,price').sort('price', true).take(20).callback(function(err, items) {
    console.log(items);
});

NOSQL('products').read().id('1abc8d001').callback(function(err, product) {
    console.log(product ? product.name : 'not found');
});

Filters

Every filter is joined with AND. Field names can be nested with a dot (address.city).

MethodMatches when
where(name, [comparer], value)the field compares with the value; comparers = (default), , !=, >, >=, <, <=
id(value), userid(value)the id or userid field equals the value (an array means "one of")
equal(obj)every key of the object equals its value
in(name, values), notin(name, values)the field is (or is not) one of the values; an array field matches when any item is one of them
between(name, a, b)the field is >= a and <= b
search(name, text, [where])the field contains the text (case-insensitive); where is 'beg' or 'end'
contains(name), empty(name)the field has a value (a non-empty array), or it does not
year(), month(), day()a part of a Date field compares with a number
query(code)a JavaScript expression with doc is true

or(fn) groups the filters added inside the function with OR:

NOSQL('users').find().where('active', true).or(function(builder) {
    builder.search('name', 'peter');
    builder.search('email', 'peter');
}).callback(console.log);

query() (and where() with only one argument) takes a raw JavaScript condition. The document is doc. Do not put user input into it.

NOSQL('orders').find().query('doc.items.length > 2 && doc.price > 100').callback(console.log);

Fields, sorting and paging

  • fields('id,name,price') returns only these fields; fields('-password,-token') returns everything except these fields.
  • sort(name, [desc]) sorts by a field; call it again for a second key. desc is true or 'desc'.
  • take(count) (alias limit()), skip(count) and first() limit the result. first() returns one object instead of an array.
  • page(page, limit) and paginate(page, limit, maxlimit) compute skip and take from a page number, which is handy with values from the query string.
function list($) {
    NOSQL('articles').find().where('published', true).sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);
}

Updating

update(data) (alias modify()) changes the documents that match the filter. Only the keys of data are written; other fields stay. The response is the number of updated documents.

NOSQL('products').update({ price: 39.9, dtupdated: NOW }).id('1abc8d001').callback(function(err, count) {
    console.log('updated', count);
});

A prefix in a key changes how the value is applied:

KeyEffect
'+stock': 5adds the number to the field (a missing field counts as 0)
'-stock': 1, '*price': 1.1, '/price': 2subtracts, multiplies or divides the field by the number
'>maxorder': 3writes the value only when it is greater than the field (a missing field takes it)
'<minprice': 9writes the value only when it is smaller than the field
'!active': 1toggles a boolean field (the value is ignored)
'=total': 'doc.price * doc.count'evaluates a JavaScript expression with doc
NOSQL('products').update({ '+stock': -1, '+sold': 1 }).id(id).callback(console.log);

In insert() the prefixes are removed: '+stock': 5 stores stock: 5 and '!active' stores true.

Removing and maintenance

remove() removes the documents that match the filter and responds with their count. Without a filter it removes all documents.

NOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(function(err, count) {
    console.log('removed', count);
});
  • clear() deletes the whole file with all documents.
  • clean() rewrites the file without the lines of removed and replaced documents.
ON('service', function(counter) {
    // once a day
    if (counter % 1440 === 0)
        NOSQL('logs').clean();
});

Getting the result

All builders end in the same way:

  • callback(fn) (alias pipe()) calls fn(err, response). In an action you can pass $, and the response goes straight to the client.
  • promise([$]) returns a Promise; with $ an error goes to $.invalid().
  • done($, fn) calls fn(response) and sends an error to $.invalid().
  • data(fn) and fail(fn) are called only with the response or only with the error.
  • error(message) turns an empty result (undefined, an empty array, 0 updated or removed) into an error.
NEWACTION('Products/detail', {
    params: '*id:UID',
    action: async function($) {
        var item = await NOSQL('products').read().id($.params.id).error('Not found').promise($);
        $.callback(item);
    }
});

debug() prints the compiled filter to the console. The operation runs on the next tick, so add every filter and option in the same synchronous chain.

NoSQL through DATA

NoSQL is also an engine of the global query builder DATA under the name nosql: DATA.find('nosql/users') is the same as NOSQL('users').find(). DATA adds a few reads that NOSQL() does not have:

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

DATA.check('nosql/users').where('email', email).callback(function(err, exists) {
    // exists is true or false
});

DATA.scalar('nosql/orders', 'sum', 'price').callback(function(err, response) {
    // response.value
});

DATA.list('nosql/orders').page(2, 20).callback(function(err, response) {
    // response.items, response.count (all matching documents), response.page, response.pages
});

scalar() computes sum, min, max, avg and count of a field; without a field it counts the documents. list() reads one page and the total count of the matching documents.

For DATA with SQL databases see QueryBuilder.

Made in Europe