NoSQL database
NOSQL(), TABLE(), database methods, the query builder and the config keys of the embedded database.
On this page
NOSQL(name) and TABLE(name) return a database stored in the databases/ folder. Database methods start a query and return a query builder; builder methods add conditions, sorting, paging and the callback. In this reference db is a database returned by NOSQL() or TABLE() and builder the query builder. The guide NoSQL database explains how the parts work together.
API
method
NOSQL(name)
Returns a NoSQL database: JSON documents stored in a text file.
NOSQL(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the database, or ~ followed by an absolute path to the file. |
Returns Database The database instance.
The database is stored in databases/{name}.nosql, one JSON document per line. The instance is created on the first call and then reused. A name that starts with ~ is an absolute path to the file; such an instance is not cached.
All operations return a query builder and run asynchronously in a queue, one after another.
NOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW });
NOSQL('users').find().where('name', 'Peter').callback(function(err, items) {
console.log(items);
});
NOSQL('~/www/backup/orders.nosql').find().callback(console.log);
method
TABLE(name)
Returns a table database: rows with a fixed schema stored in a text file.
TABLE(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the table, or ~ followed by an absolute path to the file. |
Returns Database The table instance.
The table is stored in databases/{name}.table. The first line holds the schema, each next line one row with values separated by |. The schema comes from the config key table_{name} or from alter(); until a table has a schema, its operations wait.
Column types: string, string(length), number, number(length), boolean (or bool), date and object. Columns can be separated with |, , or ;. Fields that are not in the schema are not stored. When every column has a size, rows have a fixed width. A string longer than its size is cut.
A table uses the same methods and query builder as NOSQL(). A name that starts with ~ is an absolute path to the file.
// config
table_products : id:string(20)|name:string(50)|price:number|stock:number|created:date
TABLE('products').insert({ id: UID(), name: 'Book', price: 12, stock: 5, created: NOW });
TABLE('products').find().where('price', '<', 20).sort('name').callback(console.log);
config
directory_databases : /databases/
Folder for the NoSQL and table files.
directory_databases : /databases/Default /databases/, relative to the app directory. NOSQL() and TABLE() create the folder when they need it.
config
table_{name} : column:type|column:type
Schema of the table TABLE(name).
table_{name} : column:type|column:typeColumns are name:type, separated by |, , or ;. Types: string, string(length), number, number(length), boolean, bool, date, object. When the schema in the config differs from the schema in the file, the table is rewritten to the new schema the first time it is used.
table_users : id:string(20)|name:string(50)|email:string(120)|age:number|active:boolean|created:date
config
textdb_inmemory : 0
Keeps small databases in memory for reading. Size in megabytes.
textdb_inmemory : 0Default 0 (off). A database whose file is smaller than this number of megabytes is cached in memory after it is read, and later reads use the cache. Writes keep the cache in sync or reset it.
// config
textdb_inmemory : 10
config
textdb_worker : false
Runs the NoSQL engine in a worker thread.
textdb_worker : falseDefault false. With true, and only while the web server is running, all NOSQL() and TABLE() operations run in a worker thread, so reading large files does not block the main thread. The oninsert, onupdate and onremove handlers are not called in this mode.
textdb_worker : true
method
db.find()
Finds documents. The response is an array.
db.find()Returns QueryBuilder Builder for conditions and the callback.
Alias: db.all(). Add conditions, sorting and limits to the returned builder. The callback receives (err, items, meta), where meta has count (matched documents), counter, scanned and duration.
Without sorting and pagination, reading stops as soon as take() documents are found.
NOSQL('users').find().where('active', true).sort('name').take(50).callback(function(err, items, meta) {
console.log(items.length, meta.duration);
});
method
db.find2()
Finds documents, reading the file from the end.
db.find2()Returns QueryBuilder Builder for conditions and the callback.
Like find(), but the newest documents come first, because new documents are appended to the end of the file.
NOSQL('logs').find2().take(10).callback(console.log);
method
db.read()
Reads one document. The response is the document or nothing.
db.read()Returns QueryBuilder Builder for conditions and the callback.
Alias: db.one(). Reads the file from the end and stops at the first match, so with several matches it returns the newest one.
NOSQL('users').read().id(id).fields('-password').callback(function(err, user) {
if (user)
console.log(user.name);
});
method
db.list()
Finds documents and returns a page with paging data.
db.list()Returns QueryBuilder Builder for conditions and the callback.
The response is { page, pages, limit, count, items }. count is the number of all matching documents, so use it with page() or paginate().
NOSQL('users').list().search('name', $.query.q).sort('name').paginate($.query.page, $.query.limit, 100).callback(function(err, response) {
// response.items, response.count, response.pages
});
method
db.count()
Counts matching documents. The response is { count: Number }.
db.count()Returns QueryBuilder Builder for conditions and the callback.
NOSQL('users').count().where('active', true).callback(function(err, response) {
console.log(response.count);
});
method
db.scalar(type, key, [key2])
Computes values over matching documents: min, max, sum, count or groups.
db.scalar(type, key, [key2])| Parameter | Type | Description |
|---|---|---|
type |
String |
group, min, max or sum. With one argument it is the field name. |
key? |
String |
Field to compute, or the field to group by when key2 is given. |
key2? |
String |
Field with the values, grouped by key. |
Returns QueryBuilder Builder for conditions and the callback.
scalar(type, key)orscalar(key): the response is{ count, sum, min, max }for the fieldkey.scalar('group', key): counts documents by the values ofkey, e.g.{ admin: 2, user: 10 }.scalar('group', key, key2): sumskey2by the values ofkey.scalar('max', key, key2),scalar('min', key, key2): the highest / lowest value ofkey2for each value ofkey; any other type sumskey2.
NOSQL('orders').scalar('price').where('paid', true).callback(function(err, response) {
// response: { count, sum, min, max }
});
NOSQL('orders').scalar('group', 'country', 'price').callback(function(err, response) {
// { SK: 1200, CZ: 800 }
});
method
db.stats(groupfield, datefield, key, [type])
Groups documents by a field and a period and returns min, max and count of a value.
db.stats(groupfield, datefield, key, [type])| Parameter | Type | Description |
|---|---|---|
groupfield |
String |
Field to group by. |
datefield |
String |
Field with a Date. |
key |
String |
Field with the measured value. |
type? |
String |
hourly, monthly or yearly; anything else is daily. Default: daily |
Returns QueryBuilder Builder for conditions and the callback.
The response is { [group]: { [period]: { min, max, count } } }. The period key is the date formatted as yyyyMMddHH (hourly), yyyyMMdd (default, daily), yyyyMM (monthly) or yyyy (yearly). Only documents with a Date in datefield are used.
NOSQL('measurements').stats('sensor', 'created', 'temperature', 'monthly').callback(function(err, response) {
// { sensor1: { '202201': { min: -4, max: 8, count: 744 } } }
});
method
db.insert(doc, [check])
Inserts a document. The response is 1.
db.insert(doc, [check])| Parameter | Type | Description |
|---|---|---|
doc |
Object |
The document. |
check? |
Boolean |
Insert only when no document matches the conditions of the returned builder. Default: false |
Returns QueryBuilder Builder for the callback (and for conditions with check).
The document is appended to the end of the file. Key prefixes used by update() (+, -, *, /, !, =, <, >) are removed from the keys.
With check set to true the method returns a builder for conditions: the document is inserted only when no document matches them, otherwise the response is 0.
NOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }).callback(function(err) {
console.log('Inserted');
});
NOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {
if (!count)
console.log('Exists');
});
method
db.update(data, [upsert])
Changes fields of matching documents. The response is the number of changed documents.
db.update(data, [upsert])| Parameter | Type | Description |
|---|---|---|
data |
Object |
Fields to change, with optional prefixes. |
upsert? |
Boolean |
Insert the data when no document matches. Default: false |
Returns QueryBuilder Builder for conditions and the callback.
Aliases: db.modify(), db.mod(). Only the fields in data change; other fields stay. Keys with the value undefined are skipped. A prefix in the key performs an operation with the stored value:
| Key | Operation |
|---|---|
field | Set the value |
+field | Add (a missing value counts as 0) |
-field | Subtract |
*field | Multiply |
/field | Divide |
!field | Toggle a boolean; the value is ignored |
>field | Keep the higher value |
<field | Keep the lower value |
With upsert the data (without the prefixes) is inserted as a new document when nothing matched; builder.insert(fn) can change it first.
NOSQL('products').update({ price: 15, '+version': 1, updated: NOW }).id(id).callback(function(err, count) {
console.log('Updated:', count);
});
NOSQL('visits').update({ id: url, '+count': 1 }, true).id(url);
method
db.remove()
Removes matching documents. The response is the number of removed documents.
db.remove()Returns QueryBuilder Builder for conditions and the callback.
Alias: db.rem(). Removed documents are marked in the file; clean() frees the space. Without conditions all documents are removed.
NOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {
console.log('Removed:', count);
});
method
db.clear([callback])
Removes all documents.
db.clear([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
Called when the database is empty. |
Returns QueryBuilder A builder.
A NoSQL database deletes its data file. A table keeps only its schema line.
NOSQL('cache').clear(function() {
console.log('Empty');
});
method
db.clean([callback])
Compacts the file: rewrites it without removed and outdated lines.
db.clean([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
Called when the file is rewritten. |
Returns QueryBuilder The database.
Removing a document, and updating one that grows, leaves unused lines in the file. Run clean() from time to time, e.g. once a day, to make the file smaller and reading faster.
ON('service', function(counter) {
if (counter % 1440 === 0)
NOSQL('logs').clean();
});
method
db.drop()
Deletes the database: the data file, its backups (.bk) and log (.log).
db.drop()Returns QueryBuilder A builder.
A callback set with .callback() is called when the drop is queued, with { success: true } as its first argument.
NOSQL('temporary').drop();
method
db.backups([callback])
Reads the backups made by builder.backup().
db.backups([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
function(err, items). |
Returns QueryBuilder Builder for conditions and the callback.
Backups are stored in {file}.bk, newest first. Each record has date, body (the original document as a JSON string) and the fields you passed to builder.backup(data). You can filter the records with the returned builder.
NOSQL('products').backups().where('user', 'Peter').take(20).callback(function(err, items) {
items.forEach(item => console.log(item.date, JSON.parse(item.body)));
});
method
db.usage([callback])
Returns the number of documents and the file size.
db.usage([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
function(err, response). |
Returns QueryBuilder A builder.
The response is { documents, filesize } (size in bytes). The values come from the last counting of the database; db.recount() counts the documents and measures the file again.
NOSQL('users').usage(function(err, response) {
console.log(response.documents, response.filesize);
});
method
db.memory([count], [size])
Sets the read buffer of the database.
db.memory([count], [size])| Parameter | Type | Description |
|---|---|---|
count? |
Number |
Number of documents processed at once. Default: 15 |
size? |
Number |
Size of the read buffer in kB. Default: 32 |
Larger buffers read big files faster and use more memory.
NOSQL('logs').memory(50, 128);
method
db.lock(callback)
Runs a function while no other operation of the database runs.
db.lock(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function |
function(next); call next() to release the lock. |
The callback receives next. Queued operations wait until you call it.
NOSQL('counters').lock(function(next) {
// exclusive work with the file
next();
});
method
db.alter(schema, [callback])
Sets or changes the schema of a table. Only for TABLE().
db.alter(schema, [callback])| Parameter | Type | Description |
|---|---|---|
schema |
String |
Columns as name:type, separated by |, , or ;. |
callback? |
Function |
Called when the schema is applied. |
Returns Database The table.
A new table writes the schema line. When the schema differs from the current one, the file is rewritten and existing rows get the new columns. A column written as newname=oldname:type takes the values of the old column.
TABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');
TABLE('users').alter('id:string(20)|fullname=name:string(50)|age:number|active:boolean|created:date');
delegate
db.oninsert = function(doc) {}
Called for every inserted document.
db.oninsert = function(doc) {}| Parameter | Type | Description |
|---|---|---|
doc |
Object |
The inserted document. |
Assign it before the first operation of the database. Called only by NOSQL() databases and not when textdb_worker is on.
var db = NOSQL('orders');
db.oninsert = function(doc) {
console.log('New order', doc.id);
};
delegate
db.onupdate = function(doc) {}
Called for every changed document.
db.onupdate = function(doc) {}| Parameter | Type | Description |
|---|---|---|
doc |
Object |
The document after the change. |
Assign it before the first operation of the database. Called by NOSQL() and TABLE(), not when textdb_worker is on.
NOSQL('orders').onupdate = function(doc) {
console.log('Changed order', doc.id);
};
delegate
db.onremove = function(record) {}
Called for every removed document.
db.onremove = function(record) {}| Parameter | Type | Description |
|---|---|---|
record |
String |
The removed record as stored in the file. |
Assign it before the first operation of the database. It receives the stored line of the document as a string (JSON for NOSQL()). Not called when textdb_worker is on.
NOSQL('orders').onremove = function(record) {
var doc = JSON.parse(record);
console.log('Removed order', doc.id);
};
method
builder.where(name, [operator], value)
Adds a condition that compares a field with a value.
builder.where(name, [operator], value)| Parameter | Type | Description |
|---|---|---|
name |
String |
Field name. |
operator? |
String |
Comparison operator. Default: == |
value |
Object |
Value to compare with. |
Returns QueryBuilder The same builder, for chaining.
Operators: = and == (equal), != and <> (not equal), >, <, >=, <=. With two arguments the operator is ==. A dotted name reads a nested field (address.city); a missing parent does not throw.
NOSQL('users').find().where('role', 'admin').where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);
method
builder.id(id)
Adds a condition for the field id.
builder.id(id)| Parameter | Type | Description |
|---|---|---|
id |
String|Array |
The id or an array of ids. |
Returns QueryBuilder The same builder, for chaining.
An array of ids works like in('id', ids).
NOSQL('users').read().id('3ab5k001pt51d').callback(console.log);
NOSQL('users').find().id(['a1', 'a2', 'a3']).callback(console.log);
method
builder.in(name, value, [key])
The field value must be in the array.
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.
When the field holds an array, it is enough that one of its items is in value. With key, value is an array of objects and their key property is used.
NOSQL('products').find().in('category', ['books', 'music']).callback(console.log);
NOSQL('users').find().in('id', orders, 'userid').callback(console.log);
method
builder.notin(name, value, [key])
The field value must not be in the array.
builder.notin(name, value, [key])| Parameter | Type | Description |
|---|---|---|
name |
String |
Field name. |
value |
Array |
Excluded values. |
key? |
String |
Property to read from objects in value. |
Returns QueryBuilder The same builder, for chaining.
The opposite of in(). With key, value is an array of objects and their key property is used.
NOSQL('orders').find().notin('status', ['canceled', 'deleted']).callback(console.log);
method
builder.between(name, a, b)
The field value must be between two values, both included.
builder.between(name, a, b)| Parameter | Type | Description |
|---|---|---|
name |
String |
Field name. |
a |
Number|Date|String |
Lowest value. |
b |
Number|Date|String |
Highest value. |
Returns QueryBuilder The same builder, for chaining.
NOSQL('orders').find().between('created', NOW.add('-7 days'), NOW).callback(console.log);
method
builder.search(name, value, [where])
Case-insensitive text search in a field.
builder.search(name, value, [where])| Parameter | Type | Description |
|---|---|---|
name |
String |
Field name. |
value |
String |
Searched text. |
where? |
String |
beg or end. |
Returns QueryBuilder The same builder, for chaining.
Without where the field must contain the value. beg means it starts with the value, end that it ends with it. A field with an array matches when one of its items matches. An empty field or value never matches.
NOSQL('products').find().search('name', 'phone').callback(console.log);
NOSQL('users').find().search('email', 'admin', 'beg').callback(console.log);
method
builder.contains(name)
The field must not be empty.
builder.contains(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Field name. |
Returns QueryBuilder The same builder, for chaining.
An array must have items; any other value must be truthy.
NOSQL('products').find().contains('photos').callback(console.log);
method
builder.empty(name)
The field must be empty.
builder.empty(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Field name. |
Returns QueryBuilder The same builder, for chaining.
An empty array, null, undefined, an empty string, 0 or false.
NOSQL('orders').find().empty('note').callback(console.log);
method
builder.year(name, [operator], value)
Compares the year of a date field. month() and day() compare the month (1-12) and the day of the month.
builder.year(name, [operator], value)| Parameter | Type | Description |
|---|---|---|
name |
String |
Field with a Date. |
operator? |
String |
Comparison operator. Default: = |
value |
Number |
Year, month (1-12) or day. |
Returns QueryBuilder The same builder, for chaining.
builder.month(name, [operator], value) and builder.day(name, [operator], value) work the same way. Operators are the same as in where(); the default is =. Fields without a date never match.
NOSQL('orders').find().year('created', 2022).month('created', '>=', 6).callback(console.log);
method
builder.or(fn)
Joins the conditions added inside the function with OR.
builder.or(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(builder) that adds conditions. |
Returns QueryBuilder The same builder, for chaining.
The function receives the builder (also as this). Conditions outside the function are still joined with AND.
NOSQL('products').find().where('active', true).or(function(builder) {
builder.where('stock', '>', 0);
builder.where('preorder', true);
}).callback(console.log);
method
builder.rule(code, [arg])
Adds a raw JavaScript condition.
builder.rule(code, [arg])| Parameter | Type | Description |
|---|---|---|
code |
String |
JavaScript expression, e.g. doc.age > arg.age. |
arg? |
Object |
Values for the expression. |
Returns QueryBuilder The same builder, for chaining.
code is an expression that returns a boolean. It sees doc (the document) and arg (your values; the keys of arg are copied to it). Code with the words require or global is rejected and matches nothing.
NOSQL('users').find().rule('doc.age >= arg.min && doc.age <= arg.max', { min: 18, max: 30 }).callback(console.log);
method
builder.fields(fields)
Chooses the returned fields.
builder.fields(fields)| Parameter | Type | Description |
|---|---|---|
fields |
String |
Fields, e.g. id,name,email or -password. |
Returns QueryBuilder The same builder, for chaining.
A comma-separated list. -name removes a field and keeps the others. name as title returns the field under another name.
NOSQL('users').find().fields('id,name,email').callback(console.log);
NOSQL('users').read().id(id).fields('-password').callback(console.log);
method
builder.sort(sort)
Sorts the result.
builder.sort(sort)| Parameter | Type | Description |
|---|---|---|
sort |
String |
E.g. name, created_desc or country,name_desc. |
Returns QueryBuilder The same builder, for chaining.
Alias: builder.gridsort(). name or name_asc sorts ascending, name_desc descending. Several fields are separated with commas; dotted names sort by nested fields.
NOSQL('users').find().sort('created_desc').take(10).callback(console.log);
method
builder.take(count)
Returns at most count documents.
builder.take(count)| Parameter | Type | Description |
|---|---|---|
count |
Number |
Maximum number of documents. |
Returns QueryBuilder The same builder, for chaining.
Alias: builder.limit().
NOSQL('users').find().take(5).callback(console.log);
method
builder.skip(count)
Skips the first count matching documents.
builder.skip(count)| Parameter | Type | Description |
|---|---|---|
count |
Number |
Number of documents to skip. |
Returns QueryBuilder The same builder, for chaining.
NOSQL('users').find().sort('name').skip(20).take(10).callback(console.log);
method
builder.first()
Returns only the first matching document instead of an array.
builder.first()Returns QueryBuilder The same builder, for chaining.
In a join() it makes the joined field one document (or null) instead of an array.
NOSQL('users').find().where('role', 'admin').sort('created').first().callback(console.log);
method
builder.page(page, [limit])
Selects a page. The page number starts at 0.
builder.page(page, [limit])| Parameter | Type | Description |
|---|---|---|
page |
Number |
Page index, starting at 0. |
limit? |
Number |
Documents per page. |
Returns QueryBuilder The same builder, for chaining.
Sets skip to page * limit. Without limit the value of an earlier take() is used. For page numbers from the query string, which start at 1, use paginate().
NOSQL('users').list().sort('name').page(1, 20).callback(console.log);
method
builder.paginate(page, limit, [maxlimit])
Selects a page. The page number starts at 1.
builder.paginate(page, limit, [maxlimit])| Parameter | Type | Description |
|---|---|---|
page |
Number|String |
Page number, starting at 1. |
limit |
Number|String |
Documents per page. |
maxlimit? |
Number |
Highest allowed limit. |
Returns QueryBuilder The same builder, for chaining.
Accepts strings, so values from the query can be passed as they are. A page lower than 1 becomes 1. limit is capped by maxlimit; without limit, maxlimit is used.
NOSQL('users').list().paginate($.query.page, $.query.limit, 100).callback(function(err, response) {
$.callback(response);
});
method
builder.callback(fn, [error]) or builder.callback($, [error])
Sets the function that receives the result, or connects the builder to an operation $.
builder.callback(fn, [error]) or builder.callback($, [error])| Parameter | Type | Description |
|---|---|---|
fn |
Function|Object |
function(err, response, meta) or the $ object of an operation. |
error? |
String |
Error when nothing was found, e.g. error-users-404. |
Returns QueryBuilder|Promise The builder for a function; a promise for $.
With a function, it receives (err, response, meta). With the $ of a schema operation, an error is passed to $.invalid() and the method returns a promise with the response, so you can await it.
error is used when the response is empty (nothing, 0 or an empty array): the function receives it as err, or $.invalid(error) is called.
NOSQL('users').find().callback(function(err, items, meta) {
console.log(items, meta.scanned);
});
schema.setRead(async function($) {
var item = await NOSQL('users').read().id($.id).callback($, 'error-users-404');
$.callback(item);
});
method
builder.promise([fn])
Returns a promise with the response.
builder.promise([fn])| Parameter | Type | Description |
|---|---|---|
fn? |
Function |
function(response) that returns the value for the promise. |
Returns Promise Promise with the response.
The promise rejects with the error. fn can transform the response before the promise resolves.
var items = await NOSQL('users').find().where('active', true).promise();
var count = await NOSQL('users').count().promise(response => response.count);
method
builder.done($, fn, [param])
Calls fn with the response, or $.invalid() on an error.
builder.done($, fn, [param])| Parameter | Type | Description |
|---|---|---|
$ |
Object |
The $ object of an operation. |
fn |
Function |
function(response, param). |
param? |
Object |
Value passed to fn as the second argument. |
Returns QueryBuilder The same builder, for chaining.
NOSQL('users').count().done($, function(response) {
$.callback(response.count);
});
method
builder.error(message)
Sets an error for an empty response.
builder.error(message)| Parameter | Type | Description |
|---|---|---|
message |
String |
Error message or key. |
Returns QueryBuilder The same builder, for chaining.
Alias: builder.err(). When the response is empty (nothing, 0 or an empty array), the callback receives this error, or $.invalid() is called when the builder is connected to $.
NOSQL('users').read().id(id).error('error-users-404').callback($);
method
builder.insert(fn)
Changes the document that an upsert inserts.
builder.insert(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(doc, builder). |
Returns QueryBuilder The same builder, for chaining.
Only for update(data, true). When nothing matched, fn receives the data that will be inserted and the builder.
NOSQL('stats').update({ id: key, '+count': 1, updated: NOW }, true).id(key).insert(function(doc) {
doc.created = NOW;
});
method
builder.backup([data])
Saves the original documents before an update or removal.
builder.backup([data])| Parameter | Type | Description |
|---|---|---|
data? |
Object |
Extra fields for the backup record, e.g. who made the change. |
Returns QueryBuilder The same builder, for chaining.
Each changed or removed document is appended to {file}.bk as { ...data, date, body }, where body is the original document as a JSON string. Read the backups with db.backups().
NOSQL('products').update(model).id(model.id).backup({ user: $.user.name }).callback($.done());
method
builder.join(field, database, [type])
Adds documents from another database to each result.
builder.join(field, database, [type])| Parameter | Type | Description |
|---|---|---|
field |
String |
Field that receives the joined documents. |
database |
String |
name, nosql/name or table/name. |
type? |
String |
inner; anything else is a left join. Default: left |
Returns QueryBuilder Builder for the joined database.
Returns a new builder for the joined database: set the link with on(), and use where(), fields(), take() or first() on it. A callback() on it sets the callback of the main query.
database is a NoSQL name, nosql/name or table/name. By default (left) every document is kept and field is an array (or null with first()). With inner, documents without a match are left out.
NOSQL('orders').find().where('paid', true).join('user', 'users').on('id', 'userid').fields('id,name').first().callback(function(err, items) {
// items[0].user = { id, name }
});
method
builder.on(field, parentfield)
Links a joined database to the main query.
builder.on(field, parentfield)| Parameter | Type | Description |
|---|---|---|
field |
String |
Field in the joined database. |
parentfield |
String |
Field in the documents of the main query. |
Returns QueryBuilder The same builder, for chaining.
Use it on the builder returned by join(). A joined document matches when its field equals parentfield of the main document.
NOSQL('users').find().join('orders', 'orders').on('userid', 'id').callback(console.log);
method
builder.gridfilter(name, obj, [type], [field])
Adds a condition from a filter value typed by a user.
builder.gridfilter(name, obj, [type], [field])| Parameter | Type | Description |
|---|---|---|
name |
String |
Key in obj. |
obj |
Object |
The filter values, e.g. $.query. |
type? |
Function |
String, Number, Date or Boolean. Default: String |
field? |
String |
Field to filter when it differs from name. |
Returns QueryBuilder The same builder, for chaining.
Reads obj[name] and does nothing when it is empty. The value is converted with type (String, Number, Date or Boolean):
a - baddsbetween().a, baddsin(); for strings,search()for each value joined with OR.- A string adds
search(); other types addwhere(). - For
Date:today,yesterday, a year (2022), a month number, or a date for the whole day.
var builder = NOSQL('orders').list();
builder.gridfilter('name', $.query);
builder.gridfilter('price', $.query, Number);
builder.gridfilter('created', $.query, Date);
builder.paginate($.query.page, $.query.limit, 50);
builder.callback(function(err, response) {
$.callback(response);
});
method
builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])
Sets fields, filters, sorting and paging from the query of an operation.
builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])| Parameter | Type | Description |
|---|---|---|
$ |
Object |
The $ object of a schema operation. |
allowedfields? |
String |
Extra fields, e.g. id,created:date. |
skipfields? |
String |
Schema fields to leave out, e.g. password. |
defsort? |
String|Number |
Default sorting, e.g. created_desc. A number here is maxlimit. |
maxlimit? |
Number |
Highest page size. Default: 50 |
Returns QueryBuilder The same builder, for chaining.
Reads $.query and the schema of the operation:
fields: returned fields; only schema fields andallowedfields. Without it, all of them.- Any key with the name of a schema field adds a filter with
gridfilter(). sort: e.g.name_desc; unknown fields are ignored. Without it,defsort.pageandlimit:paginate()withmaxlimit.
allowedfields adds fields that are not in the schema (name:type, where the type also adds a filter); skipfields hides schema fields.
schema.setQuery(async function($) {
var response = await NOSQL('users').list().autofill($, 'id,created:date', 'password', 'created_desc', 100).callback($);
$.callback(response);
});