NoSQL database
NOSQL(name), its query builder methods and the NoSQL engine of DATA.
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.
NOSQL(name)| Parameter | Type | Description |
|---|---|---|
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.
var db = NOSQL('users');
db.find().where('active', true).callback(console.log);
method
NOSQL(name).insert(doc)
Appends a new document.
NOSQL(name).insert(doc)| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('users').insert({ id: UID(), name: 'Peter', dtcreated: NOW }).callback(function(err, response) {
// response === 1
});
method
NOSQL(name).find()
Finds documents.
NOSQL(name).find()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.
NOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, items) {
console.log(items);
});
method
NOSQL(name).read()
Reads one document.
NOSQL(name).read()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.
NOSQL('users').read().id(id).error('Not found').callback($);
method
NOSQL(name).update(data)
Updates matching documents.
NOSQL(name).update(data)| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('products').update({ '+stock': -1, dtupdated: NOW }).id(id).callback(function(err, count) {
console.log(count);
});
NOSQL('products').update({ '-stock': 1, '*price': 1.1, '>maxorder': 3 }).id(id).callback(console.log);
method
NOSQL(name).modify(data)
Alias of update().
NOSQL(name).modify(data)| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('users').modify({ '!active': 1 }).id(id).callback(console.log);
method
NOSQL(name).remove()
Removes matching documents.
NOSQL(name).remove()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().
NOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(console.log);
method
NOSQL(name).clear()
Deletes all documents.
NOSQL(name).clear()Returns QueryBuilder Builder.
Deletes the database file. The next insert creates it again.
NOSQL('cache').clear().callback(function(err) {
console.log('empty');
});
method
NOSQL(name).clean()
Compacts the database file.
NOSQL(name).clean()Returns QueryBuilder Builder.
Rewrites the file without the lines of removed documents and of old versions of updated documents. Writes wait until it finishes.
ON('service', function(counter) {
if (counter % 1440 === 0)
NOSQL('logs').clean();
});
method
builder.where(name, [comparer], value)
Compares a field with a value.
builder.where(name, [comparer], value)| Parameter | Type | Description |
|---|---|---|
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().
NOSQL('users').find().where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);
method
builder.query(code)
Adds a raw JavaScript condition.
builder.query(code)| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.equal(obj)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
Fields and values. |
Returns QueryBuilder The same builder, for chaining.
Each key of the object must equal its value.
NOSQL('users').find().equal({ role: 'admin', active: true }).callback(console.log);
method
builder.id(id)
Filters by the id field.
builder.id(id)| Parameter | Type | Description |
|---|---|---|
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).
NOSQL('users').read().id($.params.id).callback($);
method
builder.userid(id)
Filters by the userid field.
builder.userid(id)| Parameter | Type | Description |
|---|---|---|
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).
NOSQL('notes').find().userid($).callback($);
method
builder.in(name, value, [key])
The field is one of the values.
builder.in(name, value, [key])| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('products').find().in('tags', ['usb', 'wireless']).callback(console.log);
method
builder.notin(name, value, [key])
The field is none of the values.
builder.notin(name, value, [key])| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('users').find().notin('role', ['guest', 'banned']).callback(console.log);
method
builder.between(name, a, b)
The field is between two values, inclusive.
builder.between(name, a, b)| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('orders').find().between('price', 10, 100).callback(console.log);
method
builder.search(name, value, [where])
Searches text in a field.
builder.search(name, value, [where])| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('users').find().search('email', '@example.com', 'end').callback(console.log);
method
builder.contains(name)
The field has a value.
builder.contains(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Field name. |
Returns QueryBuilder The same builder, for chaining.
Matches a truthy value, or an array with at least one item.
NOSQL('users').find().contains('photo').callback(console.log);
method
builder.empty(name)
The field has no value.
builder.empty(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Field name. |
Returns QueryBuilder The same builder, for chaining.
Matches a missing or falsy value, or an empty array.
NOSQL('products').find().empty('tags').callback(console.log);
method
builder.or(fn)
Joins a group of filters with OR.
builder.or(fn)| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.year(name, [comparer], value)| Parameter | Type | Description |
|---|---|---|
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().
NOSQL('orders').find().year('dtcreated', 2024).callback(console.log);
method
builder.month(name, [comparer], value)
Compares the month (1-12) of a Date field.
builder.month(name, [comparer], value)| Parameter | Type | Description |
|---|---|---|
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().
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.
builder.day(name, [comparer], value)| Parameter | Type | Description |
|---|---|---|
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().
NOSQL('orders').find().day('dtcreated', 1).callback(console.log);
method
builder.fields(fields)
Chooses the returned fields.
builder.fields(fields)| Parameter | Type | Description |
|---|---|---|
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').
NOSQL('users').find().fields('id,name,email').callback(console.log);
method
builder.sort(name, [desc])
Sorts the result.
builder.sort(name, [desc])| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('articles').find().sort('dtcreated', true).sort('title').callback(console.log);
method
builder.take(count)
Limits the number of documents.
builder.take(count)| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('logs').find().take(50).callback(console.log);
method
builder.limit(count)
Alias of take().
builder.limit(count)| Parameter | Type | Description |
|---|---|---|
count |
Number |
Maximum count. |
Returns QueryBuilder The same builder, for chaining.
Limits the number of documents.
NOSQL('logs').find().limit(50).callback(console.log);
method
builder.skip(count)
Skips documents.
builder.skip(count)| Parameter | Type | Description |
|---|---|---|
count |
Number |
Count to skip. |
Returns QueryBuilder The same builder, for chaining.
Skips the first count matching documents.
NOSQL('logs').find().skip(100).take(50).callback(console.log);
method
builder.first()
Returns only one document.
builder.first()Returns QueryBuilder The same builder, for chaining.
Sets take(1) and the response is an object (or undefined) instead of an array.
NOSQL('users').find().where('email', email).first().callback(console.log);
method
builder.page(page, [limit])
Sets skip from a page number.
builder.page(page, [limit])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.paginate(page, limit, [maxlimit])| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('articles').find().sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);
method
builder.debug()
Prints the compiled operation.
builder.debug()Returns QueryBuilder The same builder, for chaining.
Logs the file, the operation and the compiled filter to the console with the prefix -- NoSQL -->.
NOSQL('users').find().where('age', '>', 18).debug().callback(console.log);
method
builder.callback(fn)
Reads the result with a callback.
builder.callback(fn)| Parameter | Type | Description |
|---|---|---|
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.
NOSQL('users').find().callback(function(err, items) {
if (err)
return console.error(err);
console.log(items.length);
});
method
builder.pipe(fn)
Alias of callback().
builder.pipe(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function|Object |
function(err, response), or $. |
Returns QueryBuilder The same builder, for chaining.
fn(err, response), or $.
NOSQL('users').find().pipe($);
method
builder.promise([$])
Returns the result as a Promise.
builder.promise([$])| Parameter | Type | Description |
|---|---|---|
$? |
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().
var items = await NOSQL('users').find().where('active', true).promise($);
method
builder.done($, fn, [param])
Calls a function with the response, errors go to $.
builder.done($, fn, [param])| Parameter | Type | Description |
|---|---|---|
$ |
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().
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.
builder.data(fn)| Parameter | Type | Description |
|---|---|---|
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().
NOSQL('users').find().data(function(items) {
console.log(items);
});
method
builder.fail(fn)
Calls a function only with an error.
builder.fail(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(err). |
Returns QueryBuilder The same builder, for chaining.
fn(err) is called only when the operation fails.
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.
builder.error(message, [reverse])| Parameter | Type | Description |
|---|---|---|
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.
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.
DATA.count('nosql/' + name)| Parameter | Type | Description |
|---|---|---|
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 }.
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.
DATA.check('nosql/' + name)| Parameter | Type | Description |
|---|---|---|
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.
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.
DATA.scalar('nosql/' + name, type, key, [key2])| Parameter | Type | Description |
|---|---|---|
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.
DATA.scalar('nosql/orders', 'sum', 'price').where('paid', true).callback(function(err, response) {
console.log(response.value);
});
DATA.scalar('nosql/orders', 'group', 'status').callback(function(err, groups) {
// [{ status: 'paid', value: 12 }, { status: 'new', value: 3 }]
});
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.
$dirdatabases : StringReturns String
The directory where NOSQL() keeps its .nosql files. The default is databases in the root of the application.
$dirdatabases : /var/data/myapp/