Spanish Total.js
English
Documentation For AI agents
Contents

NoSQL database

NOSQL(name), its query builder methods and the NoSQL engine of DATA.

.md GitHub
On this page

Methods of NOSQL(name), the query builder they return (filters, fields, sorting, paging and results), the NoSQL reads of DATA and the $dirdatabases configuration key. For an introduction with examples read the guide NoSQL database.

API

method

NOSQL(name)

Returns a NoSQL database stored in a text file.
ParameterTypeDescription
name String Name of the database, or a file path with a slash.

Returns Object An object with insert(), find(), read(), update(), modify(), remove(), clear() and clean().

A plain name uses the file databases/<name>.nosql; the directory and the file are created when needed. A name with a slash is used as the file path as it is. Every method of the returned object returns a query builder.

Use a database
var db = NOSQL('users');
db.find().where('active', true).callback(console.log);
method

NOSQL(name).insert(doc)

Appends a new document.
ParameterTypeDescription
doc Object The document.

Returns QueryBuilder Builder; the response is 1.

Adds the document as a new line at the end of the file. No id is generated, so add your own. Keys with the prefixes + - * / > < store the value without the prefix, !key stores true and =key stores the value as it is. The response is 1.

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

NOSQL(name).find()

Finds documents.

Returns QueryBuilder Builder; the response is an Array.

Returns all matching documents as an array, or an empty array. Without sort() the most recently written documents come first.

Find
NOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, items) {
	console.log(items);
});
method

NOSQL(name).read()

Reads one document.

Returns QueryBuilder Builder; the response is an Object or undefined.

Returns the first matching document (the most recently written one when you do not sort), or undefined when nothing matches. Combine it with error() to answer with an error for a missing document.

Read by id
NOSQL('users').read().id(id).error('Not found').callback($);
method

NOSQL(name).update(data)

Updates matching documents.
ParameterTypeDescription
data Object Fields to write, optionally with a prefix.

Returns QueryBuilder Builder; the response is the count of updated documents.

Writes the keys of data into every matching document; other fields are kept. Without a filter all documents are updated. Key prefixes: +key, -key, *key and /key add, subtract, multiply or divide the field by the number (a missing field counts as 0), >key writes the value only when it is greater than the field and <key only when it is smaller (a missing field takes the value), !key toggles a boolean, =key evaluates a JavaScript expression with doc. The response is the number of updated documents.

Update
NOSQL('products').update({ '+stock': -1, dtupdated: NOW }).id(id).callback(function(err, count) {
	console.log(count);
});
Counters and limits
NOSQL('products').update({ '-stock': 1, '*price': 1.1, '>maxorder': 3 }).id(id).callback(console.log);
method

NOSQL(name).modify(data)

Alias of update().
ParameterTypeDescription
data Object Fields to write, optionally with a prefix.

Returns QueryBuilder Builder; the response is the count of updated documents.

Writes the keys of data into every matching document; other fields are kept. Without a filter all documents are updated. Key prefixes: +key, -key, *key and /key add, subtract, multiply or divide the field by the number (a missing field counts as 0), >key writes the value only when it is greater than the field and <key only when it is smaller (a missing field takes the value), !key toggles a boolean, =key evaluates a JavaScript expression with doc. The response is the number of updated documents.

Modify
NOSQL('users').modify({ '!active': 1 }).id(id).callback(console.log);
method

NOSQL(name).remove()

Removes matching documents.

Returns QueryBuilder Builder; the response is the count of removed documents.

Marks every matching document as removed. Without a filter all documents are removed. The response is the count of removed documents. The lines stay in the file until clean().

Remove old logs
NOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(console.log);
method

NOSQL(name).clear()

Deletes all documents.

Returns QueryBuilder Builder.

Deletes the database file. The next insert creates it again.

Clear
NOSQL('cache').clear().callback(function(err) {
	console.log('empty');
});
method

NOSQL(name).clean()

Compacts the database file.

Returns QueryBuilder Builder.

Rewrites the file without the lines of removed documents and of old versions of updated documents. Writes wait until it finishes.

Clean once a day
ON('service', function(counter) {
	if (counter % 1440 === 0)
		NOSQL('logs').clean();
});
method

builder.where(name, [comparer], value)

Compares a field with a value.
ParameterTypeDescription
name String Field name.
comparer? String Comparison operator. Default: '='
value Object Value to compare.

Returns QueryBuilder The same builder, for chaining.

Comparers: = (default), ==, <>, !=, >, >=, <, <=. = compares loosely, so '5' matches 5. The name can be nested (address.city). With only one argument it works as query().

Where
NOSQL('users').find().where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);
method

builder.query(code)

Adds a raw JavaScript condition.
ParameterTypeDescription
code String JavaScript expression.

Returns QueryBuilder The same builder, for chaining.

The condition can use doc, the document. A condition that contains require or global matches nothing. Never build it from user input.

Raw condition
NOSQL('orders').find().query('doc.items.length > 2').callback(console.log);
method

builder.equal(obj)

Adds where(key, value) for every key of an object.
ParameterTypeDescription
obj Object Fields and values.

Returns QueryBuilder The same builder, for chaining.

Each key of the object must equal its value.

Equal
NOSQL('users').find().equal({ role: 'admin', active: true }).callback(console.log);
method

builder.id(id)

Filters by the id field.
ParameterTypeDescription
id String|Array Identifier or identifiers.

Returns QueryBuilder The same builder, for chaining.

A value adds where('id', id), an array adds in('id', id).

By id
NOSQL('users').read().id($.params.id).callback($);
method

builder.userid(id)

Filters by the userid field.
ParameterTypeDescription
id String|Array|Object Identifier, identifiers, a user object or $.

Returns QueryBuilder The same builder, for chaining.

Accepts a string, an array of identifiers, an object with id, or $ (it then uses $.user.id).

Documents of the user
NOSQL('notes').find().userid($).callback($);
method

builder.in(name, value, [key])

The field is one of the values.
ParameterTypeDescription
name String Field name.
value Array Allowed values.
key? String Property to read from objects in value.

Returns QueryBuilder The same builder, for chaining.

A single value is wrapped in an array. When the field is an array, a document matches if any of its items is one of the values. With key, the values are taken from that property of the objects in value.

In
NOSQL('products').find().in('tags', ['usb', 'wireless']).callback(console.log);
method

builder.notin(name, value, [key])

The field is none of the values.
ParameterTypeDescription
name String Field name.
value Array Forbidden values.
key? String Property to read from objects in value.

Returns QueryBuilder The same builder, for chaining.

The opposite of in(), with the same arguments.

Not in
NOSQL('users').find().notin('role', ['guest', 'banned']).callback(console.log);
method

builder.between(name, a, b)

The field is between two values, inclusive.
ParameterTypeDescription
name String Field name.
a Number|Date Lower bound.
b Number|Date Upper bound.

Returns QueryBuilder The same builder, for chaining.

Works with numbers, strings and dates.

Between
NOSQL('orders').find().between('price', 10, 100).callback(console.log);
method

builder.search(name, value, [where])

Searches text in a field.
ParameterTypeDescription
name String Field name.
value String Text to find.
where? String 'beg' or 'end'.

Returns QueryBuilder The same builder, for chaining.

Case-insensitive. By default the text can be anywhere; 'beg' matches the beginning and 'end' the end. An array field matches when any item matches. % characters in the text are removed.

Search
NOSQL('users').find().search('email', '@example.com', 'end').callback(console.log);
method

builder.contains(name)

The field has a value.
ParameterTypeDescription
name String Field name.

Returns QueryBuilder The same builder, for chaining.

Matches a truthy value, or an array with at least one item.

Contains
NOSQL('users').find().contains('photo').callback(console.log);
method

builder.empty(name)

The field has no value.
ParameterTypeDescription
name String Field name.

Returns QueryBuilder The same builder, for chaining.

Matches a missing or falsy value, or an empty array.

Empty
NOSQL('products').find().empty('tags').callback(console.log);
method

builder.or(fn)

Joins a group of filters with OR.
ParameterTypeDescription
fn Function function(builder) that adds the filters.

Returns QueryBuilder The same builder, for chaining.

The function receives the builder (also as this); filters added inside it form one group where any of them can match.

Or
NOSQL('users').find().or(function(builder) {
	builder.where('role', 'admin');
	builder.where('owner', true);
}).callback(console.log);
method

builder.year(name, [comparer], value)

Compares the full year of a Date field.
ParameterTypeDescription
name String Date field.
comparer? String Comparison operator. Default: '='
value Number Value to compare.

Returns QueryBuilder The same builder, for chaining.

Documents where the field is not a Date do not match. Comparers are the same as in where().

Year
NOSQL('orders').find().year('dtcreated', 2024).callback(console.log);
method

builder.month(name, [comparer], value)

Compares the month (1-12) of a Date field.
ParameterTypeDescription
name String Date field.
comparer? String Comparison operator. Default: '='
value Number Value to compare.

Returns QueryBuilder The same builder, for chaining.

Documents where the field is not a Date do not match. Comparers are the same as in where().

Month
NOSQL('orders').find().month('dtcreated', '>=', 6).callback(console.log);
method

builder.day(name, [comparer], value)

Compares the day of the month (1-31) of a Date field.
ParameterTypeDescription
name String Date field.
comparer? String Comparison operator. Default: '='
value Number Value to compare.

Returns QueryBuilder The same builder, for chaining.

Documents where the field is not a Date do not match. Comparers are the same as in where().

Day
NOSQL('orders').find().day('dtcreated', 1).callback(console.log);
method

builder.fields(fields)

Chooses the returned fields.
ParameterTypeDescription
fields String Comma-separated field names.

Returns QueryBuilder The same builder, for chaining.

A comma-separated list of fields to return, or of fields with - to leave out ('-password,-token').

Fields
NOSQL('users').find().fields('id,name,email').callback(console.log);
method

builder.sort(name, [desc])

Sorts the result.
ParameterTypeDescription
name String Field name.
desc? Boolean|String true or 'desc' for descending order. Default: false

Returns QueryBuilder The same builder, for chaining.

Call it more times to sort by more fields. Nested fields work (address.city). Without sorting the most recently written documents come first.

Sort
NOSQL('articles').find().sort('dtcreated', true).sort('title').callback(console.log);
method

builder.take(count)

Limits the number of documents.
ParameterTypeDescription
count Number Maximum count.

Returns QueryBuilder The same builder, for chaining.

Reading stops as soon as enough documents are found, unless the result is sorted.

Take
NOSQL('logs').find().take(50).callback(console.log);
method

builder.limit(count)

Alias of take().
ParameterTypeDescription
count Number Maximum count.

Returns QueryBuilder The same builder, for chaining.

Limits the number of documents.

Limit
NOSQL('logs').find().limit(50).callback(console.log);
method

builder.skip(count)

Skips documents.
ParameterTypeDescription
count Number Count to skip.

Returns QueryBuilder The same builder, for chaining.

Skips the first count matching documents.

Skip
NOSQL('logs').find().skip(100).take(50).callback(console.log);
method

builder.first()

Returns only one document.

Returns QueryBuilder The same builder, for chaining.

Sets take(1) and the response is an object (or undefined) instead of an array.

First
NOSQL('users').find().where('email', email).first().callback(console.log);
method

builder.page(page, [limit])

Sets skip from a page number.
ParameterTypeDescription
page Number Page number from 1.
limit? Number Documents per page.

Returns QueryBuilder The same builder, for chaining.

Page numbers start at 1. limit sets take(); without it the current take() value is used.

Page
NOSQL('articles').find().sort('dtcreated', true).page(2, 20).callback(console.log);
method

builder.paginate(page, limit, [maxlimit])

Sets skip and take from untrusted values.
ParameterTypeDescription
page Number|String Page number from 1.
limit Number|String Documents per page.
maxlimit? Number Maximum and default limit.

Returns QueryBuilder The same builder, for chaining.

Accepts strings (for example from the query string). A page below 1 becomes 1; limit is capped at maxlimit, and a missing limit uses maxlimit.

Paginate in an action
NOSQL('articles').find().sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);
method

builder.debug()

Prints the compiled operation.

Returns QueryBuilder The same builder, for chaining.

Logs the file, the operation and the compiled filter to the console with the prefix -- NoSQL -->.

Debug
NOSQL('users').find().where('age', '>', 18).debug().callback(console.log);
method

builder.callback(fn)

Reads the result with a callback.
ParameterTypeDescription
fn Function|Object function(err, response), or $.

Returns QueryBuilder The same builder, for chaining.

fn(err, response) is called when the operation finishes. Pass $ in an action to send the response or the error to the client. pipe() is an alias.

Callback
NOSQL('users').find().callback(function(err, items) {
	if (err)
		return console.error(err);
	console.log(items.length);
});
method

builder.pipe(fn)

Alias of callback().
ParameterTypeDescription
fn Function|Object function(err, response), or $.

Returns QueryBuilder The same builder, for chaining.

fn(err, response), or $.

Pipe
NOSQL('users').find().pipe($);
method

builder.promise([$])

Returns the result as a Promise.
ParameterTypeDescription
$? Object Options of an action.

Returns Promise Resolves with the response.

The Promise resolves with the response. On an error it rejects, or, when $ is given, the error is sent to $.invalid().

Await
var items = await NOSQL('users').find().where('active', true).promise($);
method

builder.done($, fn, [param])

Calls a function with the response, errors go to $.
ParameterTypeDescription
$ Object Options of an action.
fn Function function(response, param).
param? Object A value passed to fn.

Returns QueryBuilder The same builder, for chaining.

On success fn(response, param) is called; an error is sent to $.invalid().

Done
NOSQL('users').read().id(id).error('Not found').done($, function(user) {
	$.callback({ name: user.name });
});
method

builder.data(fn)

Calls a function only with a response.
ParameterTypeDescription
fn Function function(response).

Returns QueryBuilder The same builder, for chaining.

fn(response) is called only when there is no error. It can be combined with callback().

Data
NOSQL('users').find().data(function(items) {
	console.log(items);
});
method

builder.fail(fn)

Calls a function only with an error.
ParameterTypeDescription
fn Function function(err).

Returns QueryBuilder The same builder, for chaining.

fn(err) is called only when the operation fails.

Fail
NOSQL('users').read().id(id).error('Not found').fail(function(err) {
	console.log(err);
});
method

builder.error(message, [reverse])

Turns an empty result into an error.
ParameterTypeDescription
message String|Number Error message.
reverse? Boolean Fail when the result is not empty. Default: false

Returns QueryBuilder The same builder, for chaining.

The operation fails with message when the response is empty: undefined, an empty array, or 0 updated or removed documents. With reverse it fails when the response is not empty, for example to stop a duplicate. err() is an alias.

Not found and duplicate
NOSQL('users').read().id(id).error('Not found').callback($);

NOSQL('users').read().where('email', email).error('E-mail is already used', true).callback(function(err) {
	// err when the e-mail exists
});
method

DATA.count('nosql/' + name)

Counts matching documents.
ParameterTypeDescription
name String Database name with the nosql/ prefix.

Returns QueryBuilder Builder; the response is { count }.

Uses the NoSQL engine through the global query builder. The response is an object { count: Number }.

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

DATA.check('nosql/' + name)

Checks if a document exists.
ParameterTypeDescription
name String Database name with the nosql/ prefix.

Returns QueryBuilder Builder; the response is a Boolean.

Stops at the first matching document. The response is true or false.

Check
DATA.check('nosql/users').where('email', email).callback(function(err, exists) {
	console.log(exists);
});
method

DATA.scalar('nosql/' + name, type, key, [key2])

Computes a sum, minimum, maximum, count or groups.
ParameterTypeDescription
name String Database name with the nosql/ prefix.
type String 'sum', 'min', 'max', 'avg', 'count' or 'group'.
key? String Field to compute or to group by. '*' (the default) counts each document as 1. Default: '*'
key2? String Field to sum per group (only with 'group').

Returns QueryBuilder Builder; the response is { value } or an Array of groups.

With type 'sum', 'min', 'max', 'avg' or 'count' the response is { value } for the field key (documents without the field are skipped; min and max work with dates too). avg is the sum divided by the count, or null when no document matches. Without key (or with '*') every matching document counts as 1, so DATA.scalar('nosql/orders', 'count') counts the documents. With 'group' the response is an array of { <key>: value, value: count }; with key2 the values of key2 are summed per group instead of counted.

Sum
DATA.scalar('nosql/orders', 'sum', 'price').where('paid', true).callback(function(err, response) {
	console.log(response.value);
});
Group
DATA.scalar('nosql/orders', 'group', 'status').callback(function(err, groups) {
	// [{ status: 'paid', value: 12 }, { status: 'new', value: 3 }]
});
Average and count
DATA.scalar('nosql/orders', 'avg', 'price').callback(function(err, response) {
	console.log(response.value); // the average price
});

DATA.scalar('nosql/orders', 'count').where('paid', true).callback(console.log);
config

$dirdatabases : String

Directory of the database files.

Returns String

The directory where NOSQL() keeps its .nosql files. The default is databases in the root of the application.

config
$dirdatabases : /var/data/myapp/
Made in Europe