---
title: NoSQL database
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/nosql/
updated: 2026-11-16T15:41:05.817Z
---

# NoSQL database

> NOSQL(), TABLE(), database methods, the query builder and the config keys of the embedded database.

`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](../../guides/nosql/) explains how the parts work together.

## API

### NOSQL(name)

Type: `method`

Returns a NoSQL database: JSON documents stored in a text file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: Insert and read
```js
NOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW });

NOSQL('users').find().where('name', 'Peter').callback(function(err, items) {
	console.log(items);
});
```

Example: A file outside the databases folder
```js
NOSQL('~/www/backup/orders.nosql').find().callback(console.log);
```

### TABLE(name)

Type: `method`

Returns a table database: rows with a fixed schema stored in a text file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.

Example: Schema in the config file
```js
// config
table_products  : id:string(20)|name:string(50)|price:number|stock:number|created:date
```

Example: Use the table
```js
TABLE('products').insert({ id: UID(), name: 'Book', price: 12, stock: 5, created: NOW });
TABLE('products').find().where('price', '<', 20).sort('name').callback(console.log);
```

### directory_databases : /databases/

Type: `config`

Folder for the NoSQL and table files.

Default `/databases/`, relative to the app directory. `NOSQL()` and `TABLE()` create the folder when they need it.

### table_{name} : column:type|column:type

Type: `config`

Schema of the table `TABLE(name)`.

Columns 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.

Example: Config
```js
table_users     : id:string(20)|name:string(50)|email:string(120)|age:number|active:boolean|created:date
```

### textdb_inmemory : 0

Type: `config`

Keeps small databases in memory for reading. Size in megabytes.

Default `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.

Example: Cache databases up to 10 MB
```js
// config
textdb_inmemory : 10
```

### textdb_worker : false

Type: `config`

Runs the NoSQL engine in a worker thread.

Default `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.

Example: Config
```js
textdb_worker : true
```

### db.find()

Type: `method`

Finds documents. The response is an array.

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.

Example: Find documents
```js
NOSQL('users').find().where('active', true).sort('name').take(50).callback(function(err, items, meta) {
	console.log(items.length, meta.duration);
});
```

### db.find2()

Type: `method`

Finds documents, reading the file from the end.

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.

Example: The last ten log entries
```js
NOSQL('logs').find2().take(10).callback(console.log);
```

### db.read()

Type: `method`

Reads one document. The response is the document or nothing.

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.

Example: Read by id
```js
NOSQL('users').read().id(id).fields('-password').callback(function(err, user) {
	if (user)
		console.log(user.name);
});
```

### db.list()

Type: `method`

Finds documents and returns a page with paging data.

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()`.

Example: A page for a grid
```js
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
});
```

### db.count()

Type: `method`

Counts matching documents. The response is `{ count: Number }`.

Returns: `QueryBuilder` Builder for conditions and the callback.

Example: Count
```js
NOSQL('users').count().where('active', true).callback(function(err, response) {
	console.log(response.count);
});
```

### db.scalar(type, key, [key2])

Type: `method`

Computes values over matching documents: min, max, sum, count or groups.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | `group`, `min`, `max` or `sum`. With one argument it is the field name. |
| `key` | `String` | no |  | Field to compute, or the field to group by when `key2` is given. |
| `key2` | `String` | no |  | Field with the values, grouped by `key`. |

Returns: `QueryBuilder` Builder for conditions and the callback.

- `scalar(type, key)` or `scalar(key)`: the response is `{ count, sum, min, max }` for the field `key`.
- `scalar('group', key)`: counts documents by the values of `key`, e.g. `{ admin: 2, user: 10 }`.
- `scalar('group', key, key2)`: sums `key2` by the values of `key`.
- `scalar('max', key, key2)`, `scalar('min', key, key2)`: the highest / lowest value of `key2` for each value of `key`; any other type sums `key2`.

Example: Statistics of a field
```js
NOSQL('orders').scalar('price').where('paid', true).callback(function(err, response) {
	// response: { count, sum, min, max }
});
```

Example: Sum by group
```js
NOSQL('orders').scalar('group', 'country', 'price').callback(function(err, response) {
	// { SK: 1200, CZ: 800 }
});
```

### db.stats(groupfield, datefield, key, [type])

Type: `method`

Groups documents by a field and a period and returns min, max and count of a value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `groupfield` | `String` | yes |  | Field to group by. |
| `datefield` | `String` | yes |  | Field with a `Date`. |
| `key` | `String` | yes |  | Field with the measured value. |
| `type` | `String` | no | `daily` | `hourly`, `monthly` or `yearly`; anything else is 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.

Example: Monthly temperatures by sensor
```js
NOSQL('measurements').stats('sensor', 'created', 'temperature', 'monthly').callback(function(err, response) {
	// { sensor1: { '202201': { min: -4, max: 8, count: 744 } } }
});
```

### db.insert(doc, [check])

Type: `method`

Inserts a document. The response is `1`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `doc` | `Object` | yes |  | The document. |
| `check` | `Boolean` | no | `false` | Insert only when no document matches the conditions of the returned builder. |

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`.

Example: Insert
```js
NOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }).callback(function(err) {
	console.log('Inserted');
});
```

Example: Insert only a unique email
```js
NOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {
	if (!count)
		console.log('Exists');
});
```

### db.update(data, [upsert])

Type: `method`

Changes fields of matching documents. The response is the number of changed documents.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | yes |  | Fields to change, with optional prefixes. |
| `upsert` | `Boolean` | no | `false` | Insert the data when no document matches. |

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.

Example: Update by id
```js
NOSQL('products').update({ price: 15, '+version': 1, updated: NOW }).id(id).callback(function(err, count) {
	console.log('Updated:', count);
});
```

Example: Upsert a counter
```js
NOSQL('visits').update({ id: url, '+count': 1 }, true).id(url);
```

### db.remove()

Type: `method`

Removes matching documents. The response is the number of removed documents.

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.

Example: Remove old documents
```js
NOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {
	console.log('Removed:', count);
});
```

### db.clear([callback])

Type: `method`

Removes all documents.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | Called when the database is empty. |

Returns: `QueryBuilder` A builder.

A NoSQL database deletes its data file. A table keeps only its schema line.

Example: Clear
```js
NOSQL('cache').clear(function() {
	console.log('Empty');
});
```

### db.clean([callback])

Type: `method`

Compacts the file: rewrites it without removed and outdated lines.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | 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.

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

### db.drop()

Type: `method`

Deletes the database: the data file, its backups (`.bk`) and log (`.log`).

Returns: `QueryBuilder` A builder.

A callback set with `.callback()` is called when the drop is queued, with `{ success: true }` as its first argument.

Example: Drop
```js
NOSQL('temporary').drop();
```

### db.backups([callback])

Type: `method`

Reads the backups made by `builder.backup()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | `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.

Example: Backups made by a user
```js
NOSQL('products').backups().where('user', 'Peter').take(20).callback(function(err, items) {
	items.forEach(item => console.log(item.date, JSON.parse(item.body)));
});
```

### db.usage([callback])

Type: `method`

Returns the number of documents and the file size.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | `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.

Example: Usage
```js
NOSQL('users').usage(function(err, response) {
	console.log(response.documents, response.filesize);
});
```

### db.memory([count], [size])

Type: `method`

Sets the read buffer of the database.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | no | `15` | Number of documents processed at once. |
| `size` | `Number` | no | `32` | Size of the read buffer in kB. |

Larger buffers read big files faster and use more memory.

Example: Bigger buffers
```js
NOSQL('logs').memory(50, 128);
```

### db.lock(callback)

Type: `method`

Runs a function while no other operation of the database runs.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(next)`; call `next()` to release the lock. |

The callback receives `next`. Queued operations wait until you call it.

Example: Lock
```js
NOSQL('counters').lock(function(next) {
	// exclusive work with the file
	next();
});
```

### db.alter(schema, [callback])

Type: `method`

Sets or changes the schema of a table. Only for `TABLE()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `schema` | `String` | yes |  | Columns as `name:type`, separated by `\|`, `,` or `;`. |
| `callback` | `Function` | no |  | 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.

Example: Declare a table
```js
TABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');
```

Example: Rename a column
```js
TABLE('users').alter('id:string(20)|fullname=name:string(50)|age:number|active:boolean|created:date');
```

### db.oninsert = function(doc) {}

Type: `delegate`

Called for every inserted document.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `doc` | `Object` | yes |  | The inserted document. |

Assign it before the first operation of the database. Called only by `NOSQL()` databases and not when `textdb_worker` is on.

Example: Log inserts
```js
var db = NOSQL('orders');
db.oninsert = function(doc) {
	console.log('New order', doc.id);
};
```

### db.onupdate = function(doc) {}

Type: `delegate`

Called for every changed document.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `doc` | `Object` | yes |  | 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.

Example: Log updates
```js
NOSQL('orders').onupdate = function(doc) {
	console.log('Changed order', doc.id);
};
```

### db.onremove = function(record) {}

Type: `delegate`

Called for every removed document.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `record` | `String` | yes |  | 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.

Example: Log removals
```js
NOSQL('orders').onremove = function(record) {
	var doc = JSON.parse(record);
	console.log('Removed order', doc.id);
};
```

### builder.where(name, [operator], value)

Type: `method`

Adds a condition that compares a field with a value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Field name. |
| `operator` | `String` | no | `==` | Comparison operator. |
| `value` | `Object` | yes |  | 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.

Example: Conditions
```js
NOSQL('users').find().where('role', 'admin').where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);
```

### builder.id(id)

Type: `method`

Adds a condition for the field `id`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String|Array` | yes |  | The id or an array of ids. |

Returns: `QueryBuilder` The same builder, for chaining.

An array of ids works like `in('id', ids)`.

Example: By id
```js
NOSQL('users').read().id('3ab5k001pt51d').callback(console.log);
```

Example: Several ids
```js
NOSQL('users').find().id(['a1', 'a2', 'a3']).callback(console.log);
```

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

Type: `method`

The field value must be in the array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Field name. |
| `value` | `Array` | yes |  | Allowed values. |
| `key` | `String` | no |  | 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.

Example: In
```js
NOSQL('products').find().in('category', ['books', 'music']).callback(console.log);
```

Example: Ids from other documents
```js
NOSQL('users').find().in('id', orders, 'userid').callback(console.log);
```

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

Type: `method`

The field value must not be in the array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Field name. |
| `value` | `Array` | yes |  | Excluded values. |
| `key` | `String` | no |  | 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.

Example: Not in
```js
NOSQL('orders').find().notin('status', ['canceled', 'deleted']).callback(console.log);
```

### builder.between(name, a, b)

Type: `method`

The field value must be between two values, both included.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Field name. |
| `a` | `Number|Date|String` | yes |  | Lowest value. |
| `b` | `Number|Date|String` | yes |  | Highest value. |

Returns: `QueryBuilder` The same builder, for chaining.

Example: Between
```js
NOSQL('orders').find().between('created', NOW.add('-7 days'), NOW).callback(console.log);
```

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

Type: `method`

Case-insensitive text search in a field.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Field name. |
| `value` | `String` | yes |  | Searched text. |
| `where` | `String` | no |  | `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.

Example: Search
```js
NOSQL('products').find().search('name', 'phone').callback(console.log);
```

Example: Starts with
```js
NOSQL('users').find().search('email', 'admin', 'beg').callback(console.log);
```

### builder.contains(name)

Type: `method`

The field must not be empty.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Field name. |

Returns: `QueryBuilder` The same builder, for chaining.

An array must have items; any other value must be truthy.

Example: With photos
```js
NOSQL('products').find().contains('photos').callback(console.log);
```

### builder.empty(name)

Type: `method`

The field must be empty.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Field name. |

Returns: `QueryBuilder` The same builder, for chaining.

An empty array, `null`, `undefined`, an empty string, `0` or `false`.

Example: Without a note
```js
NOSQL('orders').find().empty('note').callback(console.log);
```

### builder.year(name, [operator], value)

Type: `method`

Compares the year of a date field. `month()` and `day()` compare the month (1-12) and the day of the month.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Field with a `Date`. |
| `operator` | `String` | no | `=` | Comparison operator. |
| `value` | `Number` | yes |  | 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.

Example: Orders from June 2022 on
```js
NOSQL('orders').find().year('created', 2022).month('created', '>=', 6).callback(console.log);
```

### builder.or(fn)

Type: `method`

Joins the conditions added inside the function with OR.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Or
```js
NOSQL('products').find().where('active', true).or(function(builder) {
	builder.where('stock', '>', 0);
	builder.where('preorder', true);
}).callback(console.log);
```

### builder.rule(code, [arg])

Type: `method`

Adds a raw JavaScript condition.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `String` | yes |  | JavaScript expression, e.g. `doc.age > arg.age`. |
| `arg` | `Object` | no |  | 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.

Example: Rule
```js
NOSQL('users').find().rule('doc.age >= arg.min && doc.age <= arg.max', { min: 18, max: 30 }).callback(console.log);
```

### builder.fields(fields)

Type: `method`

Chooses the returned fields.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fields` | `String` | yes |  | 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.

Example: Only some fields
```js
NOSQL('users').find().fields('id,name,email').callback(console.log);
```

Example: Without a field
```js
NOSQL('users').read().id(id).fields('-password').callback(console.log);
```

### builder.sort(sort)

Type: `method`

Sorts the result.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `String` | yes |  | 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.

Example: Sort
```js
NOSQL('users').find().sort('created_desc').take(10).callback(console.log);
```

### builder.take(count)

Type: `method`

Returns at most `count` documents.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | Maximum number of documents. |

Returns: `QueryBuilder` The same builder, for chaining.

Alias: `builder.limit()`.

Example: Take
```js
NOSQL('users').find().take(5).callback(console.log);
```

### builder.skip(count)

Type: `method`

Skips the first `count` matching documents.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | Number of documents to skip. |

Returns: `QueryBuilder` The same builder, for chaining.

Example: Skip
```js
NOSQL('users').find().sort('name').skip(20).take(10).callback(console.log);
```

### builder.first()

Type: `method`

Returns only the first matching document instead of an array.

Returns: `QueryBuilder` The same builder, for chaining.

In a `join()` it makes the joined field one document (or `null`) instead of an array.

Example: First
```js
NOSQL('users').find().where('role', 'admin').sort('created').first().callback(console.log);
```

### builder.page(page, [limit])

Type: `method`

Selects a page. The page number starts at `0`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `page` | `Number` | yes |  | Page index, starting at `0`. |
| `limit` | `Number` | no |  | 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()`.

Example: Second page
```js
NOSQL('users').list().sort('name').page(1, 20).callback(console.log);
```

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

Type: `method`

Selects a page. The page number starts at `1`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `page` | `Number|String` | yes |  | Page number, starting at `1`. |
| `limit` | `Number|String` | yes |  | Documents per page. |
| `maxlimit` | `Number` | no |  | 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.

Example: From the query
```js
NOSQL('users').list().paginate($.query.page, $.query.limit, 100).callback(function(err, response) {
	$.callback(response);
});
```

### builder.callback(fn, [error]) or builder.callback($, [error])

Type: `method`

Sets the function that receives the result, or connects the builder to an operation `$`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function|Object` | yes |  | `function(err, response, meta)` or the `$` object of an operation. |
| `error` | `String` | no |  | 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.

Example: Callback
```js
NOSQL('users').find().callback(function(err, items, meta) {
	console.log(items, meta.scanned);
});
```

Example: Await in an operation
```js
schema.setRead(async function($) {
	var item = await NOSQL('users').read().id($.id).callback($, 'error-users-404');
	$.callback(item);
});
```

### builder.promise([fn])

Type: `method`

Returns a promise with the response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | no |  | `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.

Example: Await
```js
var items = await NOSQL('users').find().where('active', true).promise();
```

Example: Transform
```js
var count = await NOSQL('users').count().promise(response => response.count);
```

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

Type: `method`

Calls `fn` with the response, or `$.invalid()` on an error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` object of an operation. |
| `fn` | `Function` | yes |  | `function(response, param)`. |
| `param` | `Object` | no |  | Value passed to `fn` as the second argument. |

Returns: `QueryBuilder` The same builder, for chaining.

Example: Done
```js
NOSQL('users').count().done($, function(response) {
	$.callback(response.count);
});
```

### builder.error(message)

Type: `method`

Sets an error for an empty response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | yes |  | 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 `$`.

Example: Not found
```js
NOSQL('users').read().id(id).error('error-users-404').callback($);
```

### builder.insert(fn)

Type: `method`

Changes the document that an upsert inserts.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

Example: Upsert with extra fields
```js
NOSQL('stats').update({ id: key, '+count': 1, updated: NOW }, true).id(key).insert(function(doc) {
	doc.created = NOW;
});
```

### builder.backup([data])

Type: `method`

Saves the original documents before an update or removal.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | 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()`.

Example: Backup with the user
```js
NOSQL('products').update(model).id(model.id).backup({ user: $.user.name }).callback($.done());
```

### builder.join(field, database, [type])

Type: `method`

Adds documents from another database to each result.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `field` | `String` | yes |  | Field that receives the joined documents. |
| `database` | `String` | yes |  | `name`, `nosql/name` or `table/name`. |
| `type` | `String` | no | `left` | `inner`; anything else is a left join. |

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.

Example: Orders with their user
```js
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 }
});
```

### builder.on(field, parentfield)

Type: `method`

Links a joined database to the main query.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `field` | `String` | yes |  | Field in the joined database. |
| `parentfield` | `String` | yes |  | 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.

Example: On
```js
NOSQL('users').find().join('orders', 'orders').on('userid', 'id').callback(console.log);
```

### builder.gridfilter(name, obj, [type], [field])

Type: `method`

Adds a condition from a filter value typed by a user.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Key in `obj`. |
| `obj` | `Object` | yes |  | The filter values, e.g. `$.query`. |
| `type` | `Function` | no | `String` | `String`, `Number`, `Date` or `Boolean`. |
| `field` | `String` | no |  | 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 - b` adds `between()`.
- `a, b` adds `in()`; for strings, `search()` for each value joined with OR.
- A string adds `search()`; other types add `where()`.
- For `Date`: `today`, `yesterday`, a year (`2022`), a month number, or a date for the whole day.

Example: Filters from the query
```js
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);
});
```

### builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])

Type: `method`

Sets fields, filters, sorting and paging from the query of an operation.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | yes |  | The `$` object of a schema operation. |
| `allowedfields` | `String` | no |  | Extra fields, e.g. `id,created:date`. |
| `skipfields` | `String` | no |  | Schema fields to leave out, e.g. `password`. |
| `defsort` | `String|Number` | no |  | Default sorting, e.g. `created_desc`. A number here is `maxlimit`. |
| `maxlimit` | `Number` | no | `50` | Highest page size. |

Returns: `QueryBuilder` The same builder, for chaining.

Reads `$.query` and the schema of the operation:

- `fields`: returned fields; only schema fields and `allowedfields`. 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`.
- `page` and `limit`: `paginate()` with `maxlimit`.

`allowedfields` adds fields that are not in the schema (`name:type`, where the type also adds a filter); `skipfields` hides schema fields.

Example: Query operation
```js
schema.setQuery(async function($) {
	var response = await NOSQL('users').list().autofill($, 'id,created:date', 'password', 'created_desc', 100).callback($);
	$.callback(response);
});
```
