diff --git a/docs/Cursor.md b/docs/Cursor.md
index d3303f5..cf07df1 100644
--- a/docs/Cursor.md
+++ b/docs/Cursor.md
@@ -2,14 +2,17 @@
## Cursor ⇐ Promise
Manage access to data, be it to find, update or remove it.
-It extends Promise so that its methods are chainable & awaitable.
+It extends Promise
so that its methods (which return this
) are chainable & awaitable.
Promise
* [Cursor](#Cursor) ⇐ Promise
- * [new Cursor(db, query, [execFn], [async])](#new_Cursor_new)
+ * [new Cursor(db, query, [execFn], [hasCallback])](#new_Cursor_new)
* _instance_
+ * [.db](#Cursor+db) : [Datastore
](#Datastore)
+ * [.query](#Cursor+query) : [query
](#query)
+ * [.hasCallback](#Cursor+hasCallback) : boolean
* [.limit(limit)](#Cursor+limit) ⇒ [Cursor
](#Cursor)
* [.skip(skip)](#Cursor+skip) ⇒ [Cursor
](#Cursor)
* [.sort(sortQuery)](#Cursor+sort) ⇒ [Cursor
](#Cursor)
@@ -20,33 +23,48 @@
* [.exec(_callback)](#Cursor+exec)
* [.execAsync()](#Cursor+execAsync) ⇒ Promise.<(Array.<document>\|\*)>
* _inner_
- * [~execFn](#Cursor..execFn) : function
- * [~execFnAsync](#Cursor..execFnAsync) ⇒ Promise
+ * [~execFnWithCallback](#Cursor..execFnWithCallback) : function
+ * [~execFnWithoutCallback](#Cursor..execFnWithoutCallback) ⇒ Promise
\| \*
* [~execCallback](#Cursor..execCallback) : function
-### new Cursor(db, query, [execFn], [async])
+### new Cursor(db, query, [execFn], [hasCallback])
Create a new cursor for this collection
+**Params** -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| db | [Datastore
](#Datastore) | | The datastore this cursor is bound to
| -| query | [query
](#query) | | The query this cursor will operate on
| -| [execFn] | [execFn
](#Cursor..execFn) \| [execFnAsync
](#Cursor..execFnAsync) | | Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove
| -| [async] |boolean
| false
| If true, specifies that the execFn
is of type [execFnAsync](#Cursor..execFnAsync) rather than [execFn](#Cursor..execFn).
Datastore
](#Datastore) - The datastore this cursor is bound to
+- query [query
](#query) - The query this cursor will operate on
+- [execFn] [execFnWithoutCallback
](#Cursor..execFnWithoutCallback) | [execFnWithCallback
](#Cursor..execFnWithCallback) - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove
+- [hasCallback]boolean
= true
- If false, specifies that the execFn
is of type [execFnWithoutCallback](#Cursor..execFnWithoutCallback) rather than [execFnWithCallback](#Cursor..execFnWithCallback).
Datastore
](#Datastore)
+**Kind**: instance property of [Cursor
](#Cursor)
+**Access**: protected
+
+
+### cursor.query : [query
](#query)
+**Kind**: instance property of [Cursor
](#Cursor)
+**Access**: protected
+
+
+### cursor.hasCallback : boolean
+Determines if the [Cursor#execFn](Cursor#execFn) is an [execFnWithoutCallback](#Cursor..execFnWithoutCallback) or not.
+ +**Kind**: instance property of [Cursor
](#Cursor)
+**Access**: protected
### cursor.limit(limit) ⇒ [Cursor
](#Cursor)
Set a limit to the number of results
**Kind**: instance method of [Cursor
](#Cursor)
+**Params**
-| Param | Type |
-| --- | --- |
-| limit | Number
|
+- limit Number
@@ -54,10 +72,9 @@
Skip a number of results
**Kind**: instance method of [Cursor
](#Cursor)
+**Params**
-| Param | Type |
-| --- | --- |
-| skip | Number
|
+- skip Number
@@ -65,10 +82,9 @@
Sort results of the query
**Kind**: instance method of [Cursor
](#Cursor)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| sortQuery | Object.<string, number>
| sortQuery is { field: order }, field can use the dot-notation, order is 1 for ascending and -1 for descending
| +- sortQueryObject.<string, number>
- sortQuery is { field: order }, field can use the dot-notation, order is 1 for ascending and -1 for descending
@@ -76,21 +92,22 @@Add the use of a projection
**Kind**: instance method of [Cursor
](#Cursor)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| projection | Object.<string, number>
| MongoDB-style projection. {} means take all fields. Then it's { key1: 1, key2: 1 } to take only key1 and key2 { key1: 0, key2: 0 } to omit only key1 and key2. Except _id, you can't mix takes and omits.
| +- projectionObject.<string, number>
- MongoDB-style projection. {} means take all fields. Then it's { key1: 1, key2: 1 } to take only key1 and key2 +{ key1: 0, key2: 0 } to omit only key1 and key2. Except _id, you can't mix takes and omits.
### cursor.project(candidates) ⇒ [Array.<document>
](#document)
-Apply the projection
+Apply the projection.
+This is an internal function. You should use [execAsync](#Cursor+execAsync) or [exec](#Cursor+exec).
**Kind**: instance method of [Cursor
](#Cursor)
+**Access**: protected
+**Params**
-| Param | Type |
-| --- | --- |
-| candidates | [Array.<document>
](#document) |
+- candidates [Array.<document>
](#document)
@@ -104,14 +121,15 @@ This is an internal function, use execAsync which uses the executor
### cursor.\_exec(_callback)
Get all matching elements -Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne -This is an internal function, use exec which uses the executor
+Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne +This is an internal function, use [exec](#Cursor+exec) which uses the [executor](#Datastore+executor).
**Kind**: instance method of [Cursor
](#Cursor)
+**Access**: protected
+**See**: Cursor#exec
+**Params**
-| Param | Type |
-| --- | --- |
-| _callback | [execCallback
](#Cursor..execCallback) |
+- _callback [execCallback
](#Cursor..execCallback)
@@ -120,44 +138,44 @@ This is an internal function, use exec which uses the executor
Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne
**Kind**: instance method of [Cursor
](#Cursor)
+**Params**
-| Param | Type |
-| --- | --- |
-| _callback | [execCallback
](#Cursor..execCallback) |
+- _callback [execCallback
](#Cursor..execCallback)
### cursor.execAsync() ⇒ Promise.<(Array.<document>\|\*)>
-Get all matching elements -Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne
+Async version of [exec](#Cursor+exec).
**Kind**: instance method of [Cursor
](#Cursor)
-
+**See**: Cursor#exec
+
+
+### Cursor~execFnWithCallback : function
+Has a callback
-### Cursor~execFn :function
**Kind**: inner typedef of [Cursor
](#Cursor)
+**Params**
+
+- err Error
+- res [?Array.<document>
](#document) | [document
](#document)
-| Param | Type |
-| --- | --- |
-| err | Error
|
-| res | [?Array.<document>
](#document) \| [document
](#document) |
+
-
+### Cursor~execFnWithoutCallback ⇒ Promise
\| \*
+Does not have a callback, may return a Promise.
-### Cursor~execFnAsync ⇒Promise
**Kind**: inner typedef of [Cursor
](#Cursor)
+**Params**
-| Param | Type |
-| --- | --- |
-| res | [?Array.<document>
](#document) \| [document
](#document) |
+- res [?Array.<document>
](#document) | [document
](#document)
### Cursor~execCallback : function
**Kind**: inner typedef of [Cursor
](#Cursor)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| err | Error
| |
-| res | [Array.<document>
](#document) \| \*
| If an execFn was given to the Cursor, then the type of this parameter is the one returned by the execFn.
| +- errError
+- res [Array.<document>
](#document) | \*
- If an execFn was given to the Cursor, then the type of this parameter is the one returned by the execFn.
diff --git a/docs/Datastore.md b/docs/Datastore.md index 83ca95b..25aef46 100644 --- a/docs/Datastore.md +++ b/docs/Datastore.md @@ -5,37 +5,46 @@ **Kind**: global class **Extends**:EventEmitter
-**Emits**: Datastore.event:"compaction.done"
+**Emits**: Datastore#event:"compaction.done"
* [Datastore](#Datastore) ⇐ EventEmitter
* [new Datastore(options)](#new_Datastore_new)
* _instance_
+ * [.inMemoryOnly](#Datastore+inMemoryOnly) : boolean
+ * [.autoload](#Datastore+autoload) : boolean
+ * [.timestampData](#Datastore+timestampData) : boolean
+ * [.filename](#Datastore+filename) : string
* [.persistence](#Datastore+persistence) : [Persistence
](#Persistence)
* [.executor](#Datastore+executor) : [Executor
](#Executor)
+ * [.indexes](#Datastore+indexes) : Object.<string, Index>
+ * [.ttlIndexes](#Datastore+ttlIndexes) : Object.<string, number>
* [.autoloadPromise](#Datastore+autoloadPromise) : Promise
+ * [.compareStrings()](#Datastore+compareStrings) : [compareStrings
](#compareStrings)
* [.loadDatabase(callback)](#Datastore+loadDatabase)
* [.loadDatabaseAsync()](#Datastore+loadDatabaseAsync) ⇒ Promise
* [.getAllData()](#Datastore+getAllData) ⇒ [Array.<document>
](#document)
- * [.resetIndexes()](#Datastore+resetIndexes)
+ * [.resetIndexes(newData)](#Datastore+resetIndexes)
* [.ensureIndex(options, callback)](#Datastore+ensureIndex)
* [.ensureIndexAsync(options)](#Datastore+ensureIndexAsync) ⇒ Promise.<void>
* [.removeIndex(fieldName, callback)](#Datastore+removeIndex)
* [.removeIndexAsync(fieldName)](#Datastore+removeIndexAsync) ⇒ Promise.<void>
+ * [.addToIndexes(doc)](#Datastore+addToIndexes)
* [.removeFromIndexes(doc)](#Datastore+removeFromIndexes)
* [.updateIndexes(oldDoc, [newDoc])](#Datastore+updateIndexes)
+ * [.getCandidates(query, [dontExpireStaleDocs], callback)](#Datastore+getCandidates)
+ * [.getCandidatesAsync(query, [dontExpireStaleDocs])](#Datastore+getCandidatesAsync) ⇒ Promise.<Array.<document>>
* [.insertAsync(newDoc)](#Datastore+insertAsync) ⇒ [Promise.<document>
](#document)
* [.count(query, [callback])](#Datastore+count) ⇒ Cursor.<number>
\| undefined
* [.countAsync(query)](#Datastore+countAsync) ⇒ Cursor.<number>
* [.find(query, [projection], [callback])](#Datastore+find) ⇒ Cursor.<Array.<document>>
\| undefined
* [.findAsync(query, [projection])](#Datastore+findAsync) ⇒ Cursor.<Array.<document>>
- * [.findOne(query, projection, callback)](#Datastore+findOne) ⇒ [Cursor.<document>
](#document) \| undefined
+ * [.findOne(query, [projection], [callback])](#Datastore+findOne) ⇒ [Cursor.<document>
](#document) \| undefined
* [.findOneAsync(query, projection)](#Datastore+findOneAsync) ⇒ [Cursor.<document>
](#document)
- * [.update(query, update, [options], [cb])](#Datastore+update)
+ * [.update(query, update, [options|], [cb])](#Datastore+update)
* [.updateAsync(query, update, [options])](#Datastore+updateAsync) ⇒ Promise.<{numAffected: number, affectedDocuments: (Array.<document>\|document\|null), upsert: boolean}>
* [.remove(query, [options], [cb])](#Datastore+remove)
* [.removeAsync(query, [options])](#Datastore+removeAsync) ⇒ Promise.<number>
- * _static_
- * ["event:compaction.done"](#Datastore.event_compaction.done)
+ * ["event:compaction.done"](#Datastore+event_compaction.done)
* _inner_
* [~countCallback](#Datastore..countCallback) : function
* [~findOneCallback](#Datastore..findOneCallback) : function
@@ -51,21 +60,76 @@ function fetches the data from datafile and prepares the database. Don't
datastore, no command (insert, find, update, remove) will be executed before loadDatabase
is called, so make sure
to call it yourself or use the autoload
option.
+**Params**
+
+- options object
| string
- Can be an object or a string. If options is a string, the behavior is the same as in
+v0.6: it will be interpreted as options.filename
. Giving a string is deprecated, and will be removed in the
+next major version.
string
= null
- Path to the file where the data is persisted. If left blank, the datastore is
+automatically considered in-memory only. It cannot end with a ~
which is used in the temporary files NeDB uses to
+perform crash-safe writes.
boolean
= false
- If set to true, no data will be written in storage.
+ - [.timestampData]boolean
= false
- If set to true, createdAt and updatedAt will be created and +populated automatically (if not specified by user)
+ - [.autoload]boolean
= false
- If used, the database will automatically be loaded from the datafile
+upon creation (you don't need to call loadDatabase
). Any command issued before load is finished is buffered and
+will be executed when load is done. When autoloading is done, you can either use the onload
callback, or you can
+use this.autoloadPromise
which resolves (or rejects) when autloading is done.
function
- If you use autoloading, this is the handler called after the loadDatabase
. It
+takes one error
argument. If you use autoloading without specifying this handler, and an error happens during
+load, an error will be thrown.
function
- Hook you can use to transform data after it was serialized and
+before it is written to disk. Can be used for example to encrypt data before writing database to disk. This
+function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, which
+must absolutely not contain a \n
character (or data will be lost).
function
- Inverse of afterSerialization
. Make sure to include both and not
+just one, or you risk data loss. For the same reason, make sure both functions are inverses of one another. Some
+failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks: NeDB checks that never
+one is declared without the other, and checks that they are reverse of one another by testing on random strings of
+various lengths. In addition, if too much data is detected as corrupt, NeDB will refuse to start as it could mean
+you're not using the deserialization hook corresponding to the serialization hook used before.
number
= 0.1
- Between 0 and 1, defaults to 10%. NeDB will refuse to start +if more than this percentage of the datafile is corrupt. 0 means you don't tolerate any corruption, 1 means you +don't care.
+ - [.compareStrings] [compareStrings
](#compareStrings) - If specified, it overrides default string comparison which is not
+well adapted to non-US characters in particular accented letters. Native localCompare
will most of the time be
+the right choice.
string
- Deprecated: if you are using NeDB from whithin a Node Webkit app,
+specify its name (the same one you use in the package.json
) in this field and the filename
will be relative to
+the directory Node Webkit uses to store the rest of the application's data (local storage etc.). It works on Linux,
+OS X and Windows. Now that you can use require('nw.gui').App.dataPath
in Node Webkit to get the path to the data
+directory for your application, you should not use this option anymore and it will be removed.
boolean
+Determines if the Datastore
keeps data in-memory, or if it saves it in storage. Is not read after
+instanciation.
object
\| string
| | Can be an object or a string. If options is a string, the behavior is the same as in v0.6: it will be interpreted as options.filename
. Giving a string is deprecated, and will be removed in the next major version.
string
| null
| Path to the file where the data is persisted. If left blank, the datastore is automatically considered in-memory only. It cannot end with a ~
which is used in the temporary files NeDB uses to perform crash-safe writes.
boolean
| false
| If set to true, no data will be written in storage.
| -| [options.timestampData] |boolean
| false
| If set to true, createdAt and updatedAt will be created and populated automatically (if not specified by user)
| -| [options.autoload] |boolean
| false
| If used, the database will automatically be loaded from the datafile upon creation (you don't need to call loadDatabase
). Any command issued before load is finished is buffered and will be executed when load is done. When autoloading is done, you can either use the onload
callback, or you can use this.autoloadPromise
which resolves (or rejects) when autloading is done.
function
| | If you use autoloading, this is the handler called after the loadDatabase
. It takes one error
argument. If you use autoloading without specifying this handler, and an error happens during load, an error will be thrown.
function
| | Hook you can use to transform data after it was serialized and before it is written to disk. Can be used for example to encrypt data before writing database to disk. This function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, which must absolutely not contain a \n
character (or data will be lost).
function
| | Inverse of afterSerialization
. Make sure to include both and not just one, or you risk data loss. For the same reason, make sure both functions are inverses of one another. Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks: NeDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths. In addition, if too much data is detected as corrupt, NeDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before.
number
| 0.1
| Between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt. 0 means you don't tolerate any corruption, 1 means you don't care.
| -| [options.compareStrings] | [compareStrings
](#compareStrings) | | If specified, it overrides default string comparison which is not well adapted to non-US characters in particular accented letters. Native localCompare
will most of the time be the right choice.
string
| | Deprecated: if you are using NeDB from whithin a Node Webkit app, specify its name (the same one you use in the package.json
) in this field and the filename
will be relative to the directory Node Webkit uses to store the rest of the application's data (local storage etc.). It works on Linux, OS X and Windows. Now that you can use require('nw.gui').App.dataPath
in Node Webkit to get the path to the data directory for your application, you should not use this option anymore and it will be removed.
Datastore
](#Datastore)
+**Access**: protected
+
+
+### datastore.autoload : boolean
+Determines if the Datastore
should autoload the database upon instantiation. Is not read after instanciation.
Datastore
](#Datastore)
+**Access**: protected
+
+
+### datastore.timestampData : boolean
+Determines if the Datastore
should add createdAt
and updatedAt
fields automatically if not set by the user.
Datastore
](#Datastore)
+**Access**: protected
+
+### datastore.filename : string
+If null, it means inMemoryOnly
is true
. The filename
is the name given to the storage module. Is not read
+after instanciation.
Datastore
](#Datastore)
+**Access**: protected
### datastore.persistence : [Persistence
](#Persistence)
@@ -80,6 +144,23 @@ produced by the Datastore
and by this.persistence.compactData
to ensure operations are performed sequentially in the database.
**Kind**: instance property of [Datastore
](#Datastore)
+**Access**: protected
+
+
+### datastore.indexes : Object.<string, Index>
+Indexed by field name, dot notation can be used.
+_id is always indexed and since _ids are generated randomly the underlying binary search tree is always well-balanced
+
+**Kind**: instance property of [Datastore
](#Datastore)
+**Access**: protected
+
+
+### datastore.ttlIndexes : Object.<string, number>
+Stores the time to live (TTL) of the indexes created. The key represents the field name, the value the number of
+seconds after which data with this index field should be removed.
+
+**Kind**: instance property of [Datastore
](#Datastore)
+**Access**: protected
### datastore.autoloadPromise : Promise
@@ -87,35 +168,47 @@ to ensure operations are performed sequentially in the database.
The onload callback is not awaited by this Promise, it is started immediately after that.
**Kind**: instance property of [Datastore
](#Datastore)
+
+
+### datastore.compareStrings() : [compareStrings
](#compareStrings)
+Overrides default string comparison which is not well adapted to non-US characters in particular accented
+letters. Native localCompare
will most of the time be the right choice
+
+**Kind**: instance method of [Datastore
](#Datastore)
+**Access**: protected
### datastore.loadDatabase(callback)
Load the database from the datafile, and trigger the execution of buffered commands if any.
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type |
-| --- | --- |
-| callback | function
|
+- callback function
### datastore.loadDatabaseAsync() ⇒ Promise
-Load the database from the datafile, and trigger the execution of buffered commands if any.
+Async version of [loadDatabase](#Datastore+loadDatabase).
**Kind**: instance method of [Datastore
](#Datastore)
+**See**: Datastore#loadDatabase
### datastore.getAllData() ⇒ [Array.<document>
](#document)
-Get an array of all the data in the database
+Get an array of all the data in the database.
**Kind**: instance method of [Datastore
](#Datastore)
-### datastore.resetIndexes()
-Reset all currently defined indexes
+### datastore.resetIndexes(newData)
+Reset all currently defined indexes.
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
+
+- newData [document
](#document) | [?Array.<document>
](#document)
+
### datastore.ensureIndex(options, callback)
@@ -125,33 +218,29 @@ executor.
Previous versions said explicitly the callback was optional, it is now recommended setting one.
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| options | object
| | |
-| options.fieldName | string
| | Name of the field to index. Use the dot notation to index a field in a nested document.
|
-| [options.unique] | boolean
| false
| Enforce field uniqueness. Note that a unique index will raise an error if you try to index two documents for which the field is not defined.
|
-| [options.sparse] | boolean
| false
| don't index documents for which the field is not defined. Use this option along with "unique" if you want to accept multiple documents for which it is not defined.
|
-| [options.expireAfterSeconds] | number
| | if set, the created index is a TTL (time to live) index, that will automatically remove documents when the system date becomes larger than the date on the indexed field plus expireAfterSeconds
. Documents where the indexed field is not specified or not a Date
object are ignored
|
-| callback | [NoParamCallback
](#NoParamCallback) | | Callback, signature: err
|
+- options object
+ - .fieldName string
- Name of the field to index. Use the dot notation to index a field in a nested document.
+ - [.unique] boolean
= false
- Enforce field uniqueness. Note that a unique index will raise an error if you try to index two documents for which the field is not defined.
+ - [.sparse] boolean
= false
- don't index documents for which the field is not defined. Use this option along with "unique" if you want to accept multiple documents for which it is not defined.
+ - [.expireAfterSeconds] number
- if set, the created index is a TTL (time to live) index, that will automatically remove documents when the system date becomes larger than the date on the indexed field plus expireAfterSeconds
. Documents where the indexed field is not specified or not a Date
object are ignored
+- callback [NoParamCallback
](#NoParamCallback) - Callback, signature: err
### datastore.ensureIndexAsync(options) ⇒ Promise.<void>
-Ensure an index is kept for this field. Same parameters as lib/indexes
-This function acts synchronously on the indexes, however the persistence of the indexes is deferred with the
-executor.
-Previous versions said explicitly the callback was optional, it is now recommended setting one.
+Async version of [ensureIndex](#Datastore+ensureIndex).
**Kind**: instance method of [Datastore
](#Datastore)
+**See**: Datastore#ensureIndex
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| options | object
| | |
-| options.fieldName | string
| | Name of the field to index. Use the dot notation to index a field in a nested document.
|
-| [options.unique] | boolean
| false
| Enforce field uniqueness. Note that a unique index will raise an error if you try to index two documents for which the field is not defined.
|
-| [options.sparse] | boolean
| false
| Don't index documents for which the field is not defined. Use this option along with "unique" if you want to accept multiple documents for which it is not defined.
|
-| [options.expireAfterSeconds] | number
| | If set, the created index is a TTL (time to live) index, that will automatically remove documents when the system date becomes larger than the date on the indexed field plus expireAfterSeconds
. Documents where the indexed field is not specified or not a Date
object are ignored
|
+- options object
+ - .fieldName string
- Name of the field to index. Use the dot notation to index a field in a nested document.
+ - [.unique] boolean
= false
- Enforce field uniqueness. Note that a unique index will raise an error if you try to index two documents for which the field is not defined.
+ - [.sparse] boolean
= false
- Don't index documents for which the field is not defined. Use this option along with "unique" if you want to accept multiple documents for which it is not defined.
+ - [.expireAfterSeconds] number
- If set, the created index is a TTL (time to live) index, that will automatically remove documents when the system date becomes larger than the date on the indexed field plus expireAfterSeconds
. Documents where the indexed field is not specified or not a Date
object are ignored
@@ -160,84 +249,131 @@ Previous versions said explicitly the callback was optional, it is now recommend
Previous versions said explicitly the callback was optional, it is now recommended setting one.
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| fieldName | string
| Field name of the index to remove. Use the dot notation to remove an index referring to a field in a nested document.
|
-| callback | [NoParamCallback
](#NoParamCallback) | Optional callback, signature: err
|
+- fieldName string
- Field name of the index to remove. Use the dot notation to remove an index referring to a
+field in a nested document.
+- callback [NoParamCallback
](#NoParamCallback) - Optional callback, signature: err
### datastore.removeIndexAsync(fieldName) ⇒ Promise.<void>
-Remove an index
-Previous versions said explicitly the callback was optional, it is now recommended setting one.
+Async version of [removeIndex](#Datastore+removeIndex).
+
+**Kind**: instance method of [Datastore
](#Datastore)
+**See**: Datastore#removeIndex
+**Params**
+
+- fieldName string
- Field name of the index to remove. Use the dot notation to remove an index referring to a
+field in a nested document.
+
+
+
+### datastore.addToIndexes(doc)
+Add one or several document(s) to all indexes.
+This is an internal function.
**Kind**: instance method of [Datastore
](#Datastore)
+**Access**: protected
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| fieldName | string
| Field name of the index to remove. Use the dot notation to remove an index referring to a field in a nested document.
|
+- doc [document
](#document)
### datastore.removeFromIndexes(doc)
-Remove one or several document(s) from all indexes
+Remove one or several document(s) from all indexes.
+This is an internal function.
**Kind**: instance method of [Datastore
](#Datastore)
+**Access**: protected
+**Params**
-| Param | Type |
-| --- | --- |
-| doc | [document
](#document) |
+- doc [document
](#document)
### datastore.updateIndexes(oldDoc, [newDoc])
-Update one or several documents in all indexes
-To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs
-If one update violates a constraint, all changes are rolled back
+Update one or several documents in all indexes.
+To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs.
+If one update violates a constraint, all changes are rolled back.
+This is an internal function.
+
+**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
+
+- oldDoc [document
](#document) | Array.<{oldDoc: document, newDoc: document}>
- Document to update, or an Array
of
+{oldDoc, newDoc}
pairs.
+- [newDoc] [document
](#document) - Document to replace the oldDoc with. If the first argument is an Array
of
+{oldDoc, newDoc}
pairs, this second argument is ignored.
+
+
+
+### datastore.getCandidates(query, [dontExpireStaleDocs], callback)
+Return the list of candidates for a given query
+Crude implementation for now, we return the candidates given by the first usable index if any
+We try the following query types, in this order: basic match, $in match, comparison match
+One way to make it better would be to enable the use of multiple indexes if the first usable index
+returns too much data. I may do it in the future.
+Returned candidates will be scanned to find and remove all expired documents
+This is an internal function.
**Kind**: instance method of [Datastore
](#Datastore)
+**Access**: protected
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| oldDoc | [document
](#document) \| Array.<{oldDoc: document, newDoc: document}>
| Document to update, or an Array
of {oldDoc, newDoc}
pairs.
|
-| [newDoc] | [document
](#document) | Document to replace the oldDoc with. If the first argument is an Array
of {oldDoc, newDoc}
pairs, this second argument is ignored.
|
+- query [query
](#query)
+- [dontExpireStaleDocs] boolean
| function
= false
- If true don't remove stale docs. Useful for the remove
+function which shouldn't be impacted by expirations. If argument is not given, it is used as the callback.
+- callback [MultipleDocumentsCallback
](#MultipleDocumentsCallback) - Signature err, candidates
+
+
+
+### datastore.getCandidatesAsync(query, [dontExpireStaleDocs]) ⇒ Promise.<Array.<document>>
+Async version of [getCandidates](#Datastore+getCandidates).
+This is an internal function.
+
+**Kind**: instance method of [Datastore
](#Datastore)
+**Returns**: Promise.<Array.<document>>
- candidates
+**Access**: protected
+**See**: Datastore#getCandidates
+**Params**
+
+- query [query
](#query)
+- [dontExpireStaleDocs] boolean
= false
- If true don't remove stale docs. Useful for the remove function
+which shouldn't be impacted by expirations.
### datastore.insertAsync(newDoc) ⇒ [Promise.<document>
](#document)
-Insert a new document
-Private Use Datastore.insertAsync which has the same signature
+Async version of [Datastore#insert](Datastore#insert).
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type |
-| --- | --- |
-| newDoc | [document
](#document) \| [Array.<document>
](#document) |
+- newDoc [document
](#document) | [Array.<document>
](#document)
### datastore.count(query, [callback]) ⇒ Cursor.<number>
\| undefined
-Count all documents matching the query
+Count all documents matching the query.
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| query | [query
](#query) | MongoDB-style query
|
-| [callback] | [countCallback
](#Datastore..countCallback) | If given, the function will return undefined, otherwise it will return the Cursor.
|
+- query [query
](#query) - MongoDB-style query
+- [callback] [countCallback
](#Datastore..countCallback) - If given, the function will return undefined, otherwise it will return the Cursor.
### datastore.countAsync(query) ⇒ Cursor.<number>
-Count all documents matching the query
+Async version of [count](#Datastore+count).
**Kind**: instance method of [Datastore
](#Datastore)
**Returns**: Cursor.<number>
- count
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| query | [query
](#query) | MongoDB-style query
|
+- query [query
](#query) - MongoDB-style query
@@ -246,83 +382,105 @@ Private Use Datastore.insertAsync which has the same signature
If no callback is passed, we return the cursor so that user can limit, skip and finally exec
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| query | [query
](#query) | | MongoDB-style query
|
-| [projection] | [projection
](#projection) \| [MultipleDocumentsCallback
](#MultipleDocumentsCallback) | {}
| MongoDB-style projection. If not given, will be interpreted as the callback.
|
-| [callback] | [MultipleDocumentsCallback
](#MultipleDocumentsCallback) | | Optional callback, signature: err, docs
|
+- query [query
](#query) - MongoDB-style query
+- [projection] [projection
](#projection) | [MultipleDocumentsCallback
](#MultipleDocumentsCallback) = {}
- MongoDB-style projection. If not given, will be
+interpreted as the callback.
+- [callback] [MultipleDocumentsCallback
](#MultipleDocumentsCallback) - Optional callback, signature: err, docs
### datastore.findAsync(query, [projection]) ⇒ Cursor.<Array.<document>>
-Find all documents matching the query
-If no callback is passed, we return the cursor so that user can limit, skip and finally exec
+Async version of [find](#Datastore+find).
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| query | [query
](#query) | | MongoDB-style query
|
-| [projection] | [projection
](#projection) | {}
| MongoDB-style projection
|
+- query [query
](#query) - MongoDB-style query
+- [projection] [projection
](#projection) = {}
- MongoDB-style projection
-### datastore.findOne(query, projection, callback) ⇒ [Cursor.<document>
](#document) \| undefined
-Find one document matching the query
+### datastore.findOne(query, [projection], [callback]) ⇒ [Cursor.<document>
](#document) \| undefined
+Find one document matching the query.
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| query | [query
](#query) | MongoDB-style query
|
-| projection | [projection
](#projection) | MongoDB-style projection
|
-| callback | [SingleDocumentCallback
](#SingleDocumentCallback) | Optional callback, signature: err, doc
|
+- query [query
](#query) - MongoDB-style query
+- [projection] [projection
](#projection) | [SingleDocumentCallback
](#SingleDocumentCallback) = {}
- MongoDB-style projection
+- [callback] [SingleDocumentCallback
](#SingleDocumentCallback) - Optional callback, signature: err, doc
### datastore.findOneAsync(query, projection) ⇒ [Cursor.<document>
](#document)
-Find one document matching the query
+Async version of [findOne](#Datastore+findOne).
**Kind**: instance method of [Datastore
](#Datastore)
+**See**: Datastore#findOne
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| query | [query
](#query) | MongoDB-style query
|
-| projection | [projection
](#projection) | MongoDB-style projection
|
+- query [query
](#query) - MongoDB-style query
+- projection [projection
](#projection) - MongoDB-style projection
-### datastore.update(query, update, [options], [cb])
+### datastore.update(query, update, [options|], [cb])
Update all docs matching query.
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| query | [query
](#query) | | is the same kind of finding query you use with find
and findOne
|
-| update | [document
](#document) \| update
| | specifies how the documents should be modified. It is either a new document or a set of modifiers (you cannot use both together, it doesn't make sense!):
- A new document will replace the matched docs
- The modifiers create the fields they need to modify if they don't exist, and you can apply them to subdocs. Available field modifiers are
$set
to change a field's value, $unset
to delete a field, $inc
to increment a field's value and $min
/$max
to change field's value, only if provided value is less/greater than current value. To work on arrays, you have $push
, $pop
, $addToSet
, $pull
, and the special $each
and $slice
.
|
-| [options] | Object
| | Optional options
|
-| [options.multi] | boolean
| false
| If true, can update multiple documents
|
-| [options.upsert] | boolean
| false
| If true, can insert a new document corresponding to the update
rules if your query
doesn't match anything. If your update
is a simple object with no modifiers, it is the inserted document. In the other case, the query
is stripped from all operator recursively, and the update
is applied to it.
|
-| [options.returnUpdatedDocs] | boolean
| false
| (not Mongo-DB compatible) If true and update is not an upsert, will return the array of documents matched by the find query and updated. Updated documents will be returned even if the update did not actually modify them.
|
-| [cb] | [updateCallback
](#Datastore..updateCallback) | () => {}
| Optional callback
|
+- query [query
](#query) - is the same kind of finding query you use with find
and findOne
+- update [document
](#document) | \*
- specifies how the documents should be modified. It is either a new document or a
+set of modifiers (you cannot use both together, it doesn't make sense!):
+
+- A new document will replace the matched docs
+- The modifiers create the fields they need to modify if they don't exist, and you can apply them to subdocs.
+Available field modifiers are
$set
to change a field's value, $unset
to delete a field, $inc
to increment a
+field's value and $min
/$max
to change field's value, only if provided value is less/greater than current
+value. To work on arrays, you have $push
, $pop
, $addToSet
, $pull
, and the special $each
and $slice
.
+
+- [options|] Object
| [updateCallback
](#Datastore..updateCallback) - Optional options
+ - [.multi] boolean
= false
- If true, can update multiple documents
+ - [.upsert] boolean
= false
- If true, can insert a new document corresponding to the update
rules if
+your query
doesn't match anything. If your update
is a simple object with no modifiers, it is the inserted
+document. In the other case, the query
is stripped from all operator recursively, and the update
is applied to
+it.
+ - [.returnUpdatedDocs] boolean
= false
- (not Mongo-DB compatible) If true and update is not an upsert,
+will return the array of documents matched by the find query and updated. Updated documents will be returned even
+if the update did not actually modify them.
+- [cb] [updateCallback
](#Datastore..updateCallback) = () => {}
- Optional callback
### datastore.updateAsync(query, update, [options]) ⇒ Promise.<{numAffected: number, affectedDocuments: (Array.<document>\|document\|null), upsert: boolean}>
-Update all docs matching query.
+Async version of [update](#Datastore+update).
**Kind**: instance method of [Datastore
](#Datastore)
+**See**: Datastore#update
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| query | [query
](#query) | | is the same kind of finding query you use with find
and findOne
|
-| update | [document
](#document) \| update
| | specifies how the documents should be modified. It is either a new document or a set of modifiers (you cannot use both together, it doesn't make sense!):
- A new document will replace the matched docs
- The modifiers create the fields they need to modify if they don't exist, and you can apply them to subdocs. Available field modifiers are
$set
to change a field's value, $unset
to delete a field, $inc
to increment a field's value and $min
/$max
to change field's value, only if provided value is less/greater than current value. To work on arrays, you have $push
, $pop
, $addToSet
, $pull
, and the special $each
and $slice
.
|
-| [options] | Object
| | Optional options
|
-| [options.multi] | boolean
| false
| If true, can update multiple documents
|
-| [options.upsert] | boolean
| false
| If true, can insert a new document corresponding to the update
rules if your query
doesn't match anything. If your update
is a simple object with no modifiers, it is the inserted document. In the other case, the query
is stripped from all operator recursively, and the update
is applied to it.
|
-| [options.returnUpdatedDocs] | boolean
| false
| (not Mongo-DB compatible) If true and update is not an upsert, will return the array of documents matched by the find query and updated. Updated documents will be returned even if the update did not actually modify them.
|
+- query [query
](#query) - is the same kind of finding query you use with find
and findOne
+- update [document
](#document) | \*
- specifies how the documents should be modified. It is either a new document or a
+set of modifiers (you cannot use both together, it doesn't make sense!):
+
+- A new document will replace the matched docs
+- The modifiers create the fields they need to modify if they don't exist, and you can apply them to subdocs.
+Available field modifiers are
$set
to change a field's value, $unset
to delete a field, $inc
to increment a
+field's value and $min
/$max
to change field's value, only if provided value is less/greater than current
+value. To work on arrays, you have $push
, $pop
, $addToSet
, $pull
, and the special $each
and $slice
.
+
+- [options] Object
= {}
- Optional options
+ - [.multi] boolean
= false
- If true, can update multiple documents
+ - [.upsert] boolean
= false
- If true, can insert a new document corresponding to the update
rules if
+your query
doesn't match anything. If your update
is a simple object with no modifiers, it is the inserted
+document. In the other case, the query
is stripped from all operator recursively, and the update
is applied to
+it.
+ - [.returnUpdatedDocs] boolean
= false
- (not Mongo-DB compatible) If true and update is not an upsert,
+will return the array of documents matched by the find query and updated. Updated documents will be returned even
+if the update did not actually modify them.
@@ -330,13 +488,12 @@ If no callback is passed, we return the cursor so that user can limit, skip and
Remove all docs matching the query.
**Kind**: instance method of [Datastore
](#Datastore)
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| query | [query
](#query) | | |
-| [options] | object
| | Optional options
|
-| [options.multi] | boolean
| false
| If true, can update multiple documents
|
-| [cb] | [removeCallback
](#Datastore..removeCallback) | () => {}
| Optional callback, signature: err, numRemoved
|
+- query [query
](#query)
+- [options] object
| [removeCallback
](#Datastore..removeCallback) = {}
- Optional options
+ - [.multi] boolean
= false
- If true, can update multiple documents
+- [cb] [removeCallback
](#Datastore..removeCallback) = () => {}
- Optional callback
@@ -346,14 +503,13 @@ Use Datastore.removeAsync which has the same signature
**Kind**: instance method of [Datastore
](#Datastore)
**Returns**: Promise.<number>
- How many documents were removed
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| query | [query
](#query) | | |
-| [options] | object
| | Optional options
|
-| [options.multi] | boolean
| false
| If true, can update multiple documents
|
+- query [query
](#query)
+- [options] object
= {}
- Optional options
+ - [.multi] boolean
= false
- If true, can update multiple documents
-
+
### "event:compaction.done"
Compaction event. Happens when the Datastore's Persistence has been compacted.
@@ -365,21 +521,19 @@ It happens when calling datastore.persistence.compactDatafile
, whic
### Datastore~countCallback : function
**Kind**: inner typedef of [Datastore
](#Datastore)
+**Params**
-| Param | Type |
-| --- | --- |
-| err | Error
|
-| count | number
|
+- err Error
+- count number
### Datastore~findOneCallback : function
**Kind**: inner typedef of [Datastore
](#Datastore)
+**Params**
-| Param | Type |
-| --- | --- |
-| err | Error
|
-| doc | [document
](#document) |
+- err Error
+- doc [document
](#document)
@@ -400,21 +554,19 @@ or running another find query on the whole dataset to check its size. Both optio
was necessary.
**Kind**: inner typedef of [Datastore
](#Datastore)
+**Params**
-| Param | Type |
-| --- | --- |
-| err | Error
|
-| numAffected | number
|
-| affectedDocuments | [?Array.<document>
](#document) \| [document
](#document) |
-| upsert | boolean
|
+- err Error
+- numAffected number
+- affectedDocuments [?Array.<document>
](#document) | [document
](#document)
+- upsert boolean
### Datastore~removeCallback : function
**Kind**: inner typedef of [Datastore
](#Datastore)
+**Params**
-| Param | Type |
-| --- | --- |
-| err | Error
|
-| numRemoved | number
|
+- err Error
+- numRemoved number
diff --git a/docs/Executor.md b/docs/Executor.md
index 47ca3f7..1d24696 100644
--- a/docs/Executor.md
+++ b/docs/Executor.md
@@ -8,10 +8,6 @@ Has an option for a buffer that can be triggered afterwards.
* [Executor](#Executor)
* [new Executor()](#new_Executor_new)
- * [.ready](#Executor+ready) : boolean
- * [.queue](#Executor+queue) : [Waterfall
](#Waterfall)
- * [.buffer](#Executor+buffer) : [Waterfall
](#Waterfall)
- * [._triggerBuffer()](#Executor+_triggerBuffer)
* [.push(task, [forceQueuing])](#Executor+push)
* [.pushAsync(task, [forceQueuing])](#Executor+pushAsync) ⇒ Promise.<\*>
* [.processBuffer()](#Executor+processBuffer)
@@ -21,35 +17,6 @@ Has an option for a buffer that can be triggered afterwards.
### new Executor()
Instantiates a new Executor.
-
-
-### executor.ready : boolean
-If this.ready is false
, then every task pushed will be buffered until this.processBuffer is called.
-
-**Kind**: instance property of [Executor
](#Executor)
-**Access**: protected
-
-
-### executor.queue : [Waterfall
](#Waterfall)
-The main queue
-
-**Kind**: instance property of [Executor
](#Executor)
-**Access**: protected
-
-
-### executor.buffer : [Waterfall
](#Waterfall)
-The buffer queue
-
-**Kind**: instance property of [Executor
](#Executor)
-**Access**: protected
-
-
-### executor.\_triggerBuffer()
-Method to trigger the buffer processing.
-Do not be use directly, use this.processBuffer
instead.
-
-**Kind**: instance method of [Executor
](#Executor)
-**Access**: protected
### executor.push(task, [forceQueuing])
@@ -57,27 +24,29 @@ Has an option for a buffer that can be triggered afterwards.
If not, buffer task for later processing
**Kind**: instance method of [Executor
](#Executor)
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| task | Object
| | |
-| task.this | Object
| | Object to use as this
|
-| task.fn | function
| | Function to execute
|
-| task.arguments | Array
| | Array of arguments, IMPORTANT: only the last argument may be a function (the callback) and the last argument cannot be false/undefined/null
|
-| [forceQueuing] | Boolean
| false
| Optional (defaults to false) force executor to queue task even if it is not ready
|
+- task Object
+ - .this Object
- Object to use as this
+ - .fn function
- Function to execute
+ - .arguments Array
- Array of arguments, IMPORTANT: only the last argument may be a function
+(the callback) and the last argument cannot be false/undefined/null
+- [forceQueuing] Boolean
= false
- Optional (defaults to false) force executor to queue task even if it is not ready
### executor.pushAsync(task, [forceQueuing]) ⇒ Promise.<\*>
-If executor is ready, queue task (and process it immediately if executor was idle)
-If not, buffer task for later processing
+Async version of [push](#Executor+push).
+This version is way simpler than its callbackEquivalent: you give it an async function task
, it is executed when
+all the previous tasks are done, and then resolves or rejects and when it is finished with its original result or
+error.
**Kind**: instance method of [Executor
](#Executor)
+**See**: Executor#push
+**Params**
-| Param | Type | Default |
-| --- | --- | --- |
-| task | function
| |
-| [forceQueuing] | boolean
| false
|
+- task [AsyncFunction
](#AsyncFunction)
+- [forceQueuing] boolean
= false
diff --git a/docs/Index.md b/docs/Index.md
index 202cea0..fd1716d 100644
--- a/docs/Index.md
+++ b/docs/Index.md
@@ -29,13 +29,12 @@ fields to be undefined
All methods on an index guarantee that either the whole operation was successful and the index changed
or the operation was unsuccessful and an error is thrown while the index is unchanged
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| options | object
| | |
-| options.fieldName | string
| | On which field should the index apply (can use dot notation to index on sub fields)
|
-| [options.unique] | boolean
| false
| Enforces a unique constraint
|
-| [options.sparse] | boolean
| false
| Allows a sparse index (we can have documents for which fieldName is undefined
)
|
+- options object
+ - .fieldName string
- On which field should the index apply (can use dot notation to index on sub fields)
+ - [.unique] boolean
= false
- Enforces a unique constraint
+ - [.sparse] boolean
= false
- Allows a sparse index (we can have documents for which fieldName is undefined
)
@@ -73,10 +72,10 @@ or the operation was unsuccessful and an error is thrown while the index is unch
Reset an index
**Kind**: instance method of [Index
](#Index)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| [newData] | [document
](#document) \| [?Array.<document>
](#document) | Data to initialize the index with. If an error is thrown during insertion, the index is not modified.
|
+- [newData] [document
](#document) | [?Array.<document>
](#document) - Data to initialize the index with. If an error is thrown during
+insertion, the index is not modified.
@@ -86,10 +85,9 @@ If an array is passed, we insert all its elements (if one insertion fails the in
O(log(n))
**Kind**: instance method of [Index
](#Index)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| doc | [document
](#document) \| [Array.<document>
](#document) | The document, or array of documents, to insert.
|
+- doc [document
](#document) | [Array.<document>
](#document) - The document, or array of documents, to insert.
@@ -100,10 +98,9 @@ The remove operation is safe with regards to the 'unique' constraint
O(log(n))
**Kind**: instance method of [Index
](#Index)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| doc | [Array.<document>
](#document) \| [document
](#document) | The document, or Array of documents, to remove.
|
+- doc [Array.<document>
](#document) | [document
](#document) - The document, or Array of documents, to remove.
@@ -113,11 +110,12 @@ If a constraint is violated, changes are rolled back and an error thrown
Naive implementation, still in O(log(n))
**Kind**: instance method of [Index
](#Index)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| oldDoc | [document
](#document) \| Array.<{oldDoc: document, newDoc: document}>
| Document to update, or an Array
of {oldDoc, newDoc}
pairs.
|
-| [newDoc] | [document
](#document) | Document to replace the oldDoc with. If the first argument is an Array
of {oldDoc, newDoc}
pairs, this second argument is ignored.
|
+- oldDoc [document
](#document) | Array.<{oldDoc: document, newDoc: document}>
- Document to update, or an Array
of
+{oldDoc, newDoc}
pairs.
+- [newDoc] [document
](#document) - Document to replace the oldDoc with. If the first argument is an Array
of
+{oldDoc, newDoc}
pairs, this second argument is ignored.
@@ -125,11 +123,10 @@ Naive implementation, still in O(log(n))
Revert an update
**Kind**: instance method of [Index
](#Index)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| oldDoc | [document
](#document) \| Array.<{oldDoc: document, newDoc: document}>
| Document to revert to, or an Array
of {oldDoc, newDoc}
pairs.
|
-| [newDoc] | [document
](#document) | Document to revert from. If the first argument is an Array of {oldDoc, newDoc}, this second argument is ignored.
|
+- oldDoc [document
](#document) | Array.<{oldDoc: document, newDoc: document}>
- Document to revert to, or an Array
of {oldDoc, newDoc}
pairs.
+- [newDoc] [document
](#document) - Document to revert from. If the first argument is an Array of {oldDoc, newDoc}, this second argument is ignored.
@@ -137,10 +134,9 @@ Naive implementation, still in O(log(n))
Get all documents in index whose key match value (if it is a Thing) or one of the elements of value (if it is an array of Things)
**Kind**: instance method of [Index
](#Index)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| value | Array.<\*>
\| \*
| Value to match the key against
|
+- value Array.<\*>
| \*
- Value to match the key against
@@ -149,14 +145,13 @@ Naive implementation, still in O(log(n))
Documents are sorted by key
**Kind**: instance method of [Index
](#Index)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| query | object
| An object with at least one matcher among $gt, $gte, $lt, $lte.
|
-| [query.$gt] | \*
| Greater than matcher.
|
-| [query.$gte] | \*
| Greater than or equal matcher.
|
-| [query.$lt] | \*
| Lower than matcher.
|
-| [query.$lte] | \*
| Lower than or equal matcher.
|
+- query object
- An object with at least one matcher among $gt, $gte, $lt, $lte.
+ - [.$gt] \*
- Greater than matcher.
+ - [.$gte] \*
- Greater than or equal matcher.
+ - [.$lt] \*
- Lower than matcher.
+ - [.$lte] \*
- Lower than or equal matcher.
diff --git a/docs/Persistence.md b/docs/Persistence.md
index d660e09..1b4c51c 100644
--- a/docs/Persistence.md
+++ b/docs/Persistence.md
@@ -8,7 +8,7 @@
* [Persistence](#Persistence)
* [new Persistence()](#new_Persistence_new)
* _instance_
- * [.persistCachedDatabase(callback)](#Persistence+persistCachedDatabase)
+ * [.persistCachedDatabase([callback])](#Persistence+persistCachedDatabase)
* [.persistCachedDatabaseAsync()](#Persistence+persistCachedDatabaseAsync) ⇒ Promise.<void>
* [.compactDatafile([callback])](#Persistence+compactDatafile)
* [.compactDatafileAsync()](#Persistence+compactDatafileAsync)
@@ -33,70 +33,69 @@
### new Persistence()
Create a new Persistence object for database options.db
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| options.db | [Datastore
](#Datastore) | |
-| [options.corruptAlertThreshold] | Number
| Optional, threshold after which an alert is thrown if too much data is corrupt
|
-| [options.nodeWebkitAppName] | string
| Optional, specify the name of your NW app if you want options.filename to be relative to the directory where Node Webkit stores application data such as cookies and local storage (the best place to store data in my opinion)
|
-| [options.beforeDeserialization] | function
| Hook you can use to transform data after it was serialized and before it is written to disk.
|
-| [options.afterSerialization] | function
| Inverse of afterSerialization
.
|
+ - .db [Datastore
](#Datastore)
+ - [.corruptAlertThreshold] Number
- Optional, threshold after which an alert is thrown if too much data is corrupt
+ - [.nodeWebkitAppName] string
- Optional, specify the name of your NW app if you want options.filename to be relative to the directory where Node Webkit stores application data such as cookies and local storage (the best place to store data in my opinion)
+ - [.beforeDeserialization] [serializationHook
](#serializationHook) - Hook you can use to transform data after it was serialized and before it is written to disk.
+ - [.afterSerialization] [serializationHook
](#serializationHook) - Inverse of afterSerialization
.
-### persistence.persistCachedDatabase(callback)
+### persistence.persistCachedDatabase([callback])
Persist cached database
This serves as a compaction function since the cache always contains only the number of documents in the collection
-while the data file is append-only so it may grow larger
-This is an internal function, use compactDataFile which uses the executor
+while the data file is append-only so it may grow larger
+This is an internal function, use [compactDatafile](#Persistence+compactDatafile) which uses the [executor](#Datastore+executor).
**Kind**: instance method of [Persistence
](#Persistence)
+**Access**: protected
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| callback | [NoParamCallback
](#NoParamCallback) | Optional callback, signature: err
|
+- [callback] [NoParamCallback
](#NoParamCallback) = () => {}
### persistence.persistCachedDatabaseAsync() ⇒ Promise.<void>
-Persist cached database
-This serves as a compaction function since the cache always contains only the number of documents in the collection
-while the data file is append-only so it may grow larger
-This is an internal function, use compactDataFileAsync which uses the executor
+Async version of [persistCachedDatabase](#Persistence+persistCachedDatabase).
+This is an internal function, use [compactDatafileAsync](#Persistence+compactDatafileAsync) which uses the [executor](#Datastore+executor).
**Kind**: instance method of [Persistence
](#Persistence)
+**Access**: protected
+**See**: Persistence#persistCachedDatabase
### persistence.compactDatafile([callback])
Queue a rewrite of the datafile
**Kind**: instance method of [Persistence
](#Persistence)
+**See**: Persistence#persistCachedDatabase
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| [callback] | [NoParamCallback
](#NoParamCallback) | () => {}
| Optional callback, signature: err
|
+- [callback] [NoParamCallback
](#NoParamCallback) = () => {}
### persistence.compactDatafileAsync()
-Queue a rewrite of the datafile
+Async version of [compactDatafile](#Persistence+compactDatafile).
**Kind**: instance method of [Persistence
](#Persistence)
+**See**: Persistence#compactDatafile
### persistence.setAutocompactionInterval(interval)
-Set automatic compaction every interval ms
+Set automatic compaction every interval
ms
**Kind**: instance method of [Persistence
](#Persistence)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| interval | Number
| in milliseconds, with an enforced minimum of 5 seconds
|
+- interval Number
- in milliseconds, with an enforced minimum of 5000 milliseconds
### persistence.stopAutocompaction()
-Stop autocompaction (do nothing if autocompaction was not running)
+Stop autocompaction (do nothing if automatic compaction was not running)
**Kind**: instance method of [Persistence
](#Persistence)
@@ -104,59 +103,68 @@ This is an internal function, use compactDataFileAsync which uses the executor
### persistence.persistNewState(newDocs, [callback])
Persist new state for the given newDocs (can be insertion, update or removal)
Use an append-only format
+Do not use directly, it should only used by a [Datastore](#Datastore) instance.
**Kind**: instance method of [Persistence
](#Persistence)
+**Access**: protected
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| newDocs | Array.<string>
| | Can be empty if no doc was updated/removed
|
-| [callback] | [NoParamCallback
](#NoParamCallback) | () => {}
| Optional, signature: err
|
+- newDocs Array.<string>
- Can be empty if no doc was updated/removed
+- [callback] [NoParamCallback
](#NoParamCallback) = () => {}
### persistence.persistNewStateAsync(newDocs) ⇒ Promise
-Persist new state for the given newDocs (can be insertion, update or removal)
-Use an append-only format
+Async version of [persistNewState](#Persistence+persistNewState)
+Do not use directly, it should only used by a [Datastore](#Datastore) instance.
**Kind**: instance method of [Persistence
](#Persistence)
+**See**: Persistence#persistNewState
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| newDocs | [Array.<document>
](#document) | Can be empty if no doc was updated/removed
|
+- newDocs [Array.<document>
](#document) - Can be empty if no doc was updated/removed
### persistence.treatRawData(rawData) ⇒ Object
-From a database's raw data, return the corresponding machine understandable collection
+From a database's raw data, return the corresponding machine understandable collection.
+Do not use directly, it should only used by a [Datastore](#Datastore) instance.
**Kind**: instance method of [Persistence
](#Persistence)
+**Access**: protected
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| rawData | string
| database file
|
+- rawData string
- database file
### persistence.treatRawStream(rawStream, cb)
-From a database's raw data stream, return the corresponding machine understandable collection
+From a database's raw data stream, return the corresponding machine understandable collection
+Is only used by a [Datastore](#Datastore) instance.
+Is only used in the Node.js version, since [React-Native](#module_storageReactNative) &
+[browser](#module_storageBrowser) storage modules don't provide an equivalent of
+[readFileStream](#module_storage.readFileStream).
+Do not use directly, it should only used by a [Datastore](#Datastore) instance.
**Kind**: instance method of [Persistence
](#Persistence)
+**Access**: protected
+**Params**
-| Param | Type |
-| --- | --- |
-| rawStream | Readable
|
-| cb | [treatRawStreamCallback
](#Persistence..treatRawStreamCallback) |
+- rawStream Readable
+- cb [treatRawStreamCallback
](#Persistence..treatRawStreamCallback)
### persistence.treatRawStreamAsync(rawStream) ⇒ Promise.<{data: Array.<document>, indexes: Object.<string, rawIndex>}>
-From a database's raw data stream, return the corresponding machine understandable collection
+Async version of [treatRawStream](#Persistence+treatRawStream).
+Do not use directly, it should only used by a [Datastore](#Datastore) instance.
**Kind**: instance method of [Persistence
](#Persistence)
+**Access**: protected
+**See**: Persistence#treatRawStream
+**Params**
-| Param | Type |
-| --- | --- |
-| rawStream | Readable
|
+- rawStream Readable
@@ -165,54 +173,47 @@ Use an append-only format
- Create all indexes
- Insert all data
-- Compact the database
-This means pulling data out of the data file or creating it if it doesn't exist
-Also, all data is persisted right away, which has the effect of compacting the database file
-This operation is very quick at startup for a big collection (60ms for ~10k docs)
+- Compact the database
+This means pulling data out of the data file or creating it if it doesn't exist
+Also, all data is persisted right away, which has the effect of compacting the database file
+This operation is very quick at startup for a big collection (60ms for ~10k docs)
+Do not use directly as it does not use the [Executor](Datastore.executor), use [loadDatabase](#Datastore+loadDatabase) instead.
**Kind**: instance method of [Persistence
](#Persistence)
+**Access**: protected
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| callback | [NoParamCallback
](#NoParamCallback) | Optional callback, signature: err
|
+- callback [NoParamCallback
](#NoParamCallback)
### persistence.loadDatabaseAsync() ⇒ Promise.<void>
-Load the database
-
-- Create all indexes
-- Insert all data
-- Compact the database
-This means pulling data out of the data file or creating it if it doesn't exist
-Also, all data is persisted right away, which has the effect of compacting the database file
-This operation is very quick at startup for a big collection (60ms for ~10k docs)
-
+Async version of [loadDatabase](#Persistence+loadDatabase)
**Kind**: instance method of [Persistence
](#Persistence)
+**See**: Persistence#loadDatabase
### Persistence.ensureDirectoryExists(dir, [callback])
-Check if a directory stat and create it on the fly if it is not the case
+Check if a directory stat and create it on the fly if it is not the case.
**Kind**: static method of [Persistence
](#Persistence)
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| dir | string
| | |
-| [callback] | [NoParamCallback
](#NoParamCallback) | () => {}
| optional callback, signature: err
|
+- dir string
+- [callback] [NoParamCallback
](#NoParamCallback) = () => {}
### Persistence.ensureDirectoryExistsAsync(dir) ⇒ Promise.<void>
-Check if a directory stat and create it on the fly if it is not the case
+Async version of [ensureDirectoryExists](#Persistence.ensureDirectoryExists).
**Kind**: static method of [Persistence
](#Persistence)
+**See**: Persistence.ensureDirectoryExists
+**Params**
-| Param | Type |
-| --- | --- |
-| dir | string
|
+- dir string
@@ -223,19 +224,19 @@ This operation is very quick at startup for a big collection (60ms for ~10k docs
data for this application. Probably the best place to store data
**Kind**: static method of [Persistence
](#Persistence)
+**Params**
-| Param | Type |
-| --- | --- |
-| appName | string
|
-| relativeFilename | string
|
+- appName string
+- relativeFilename string
### Persistence~treatRawStreamCallback : function
**Kind**: inner typedef of [Persistence
](#Persistence)
+**Params**
-| Param | Type |
-| --- | --- |
-| err | Error
|
-| data | Object
|
+- err Error
+- data object
+ - .data [Array.<document>
](#document)
+ - .indexes Object.<string, rawIndex>
diff --git a/docs/Waterfall.md b/docs/Waterfall.md
index 4091ea2..b253438 100644
--- a/docs/Waterfall.md
+++ b/docs/Waterfall.md
@@ -1,11 +1,12 @@
## Waterfall
+Responsible for sequentially executing actions on the database
+
**Kind**: global class
* [Waterfall](#Waterfall)
* [new Waterfall()](#new_Waterfall_new)
- * [._guardian](#Waterfall+_guardian) : Promise
* [.guardian](#Waterfall+guardian) ⇒ Promise
* [.waterfall(func)](#Waterfall+waterfall) ⇒ [AsyncFunction
](#AsyncFunction)
* [.chain(promise)](#Waterfall+chain) ⇒ Promise
@@ -15,15 +16,6 @@
### new Waterfall()
Instantiate a new Waterfall.
-
-
-### waterfall.\_guardian : Promise
-This is the internal Promise object which resolves when all the tasks of the Waterfall
are done.
-It will change any time this.waterfall
is called.
-Use [guardian](#Waterfall+guardian) instead which retrievethe latest version of the guardian.
-
-**Kind**: instance property of [Waterfall
](#Waterfall)
-**Access**: protected
### waterfall.guardian ⇒ Promise
@@ -35,10 +27,9 @@
### waterfall.waterfall(func) ⇒ [AsyncFunction
](#AsyncFunction)
**Kind**: instance method of [Waterfall
](#Waterfall)
+**Params**
-| Param | Type |
-| --- | --- |
-| func | [AsyncFunction
](#AsyncFunction) |
+- func [AsyncFunction
](#AsyncFunction)
@@ -46,8 +37,7 @@
Shorthand for chaining a promise to the Waterfall
**Kind**: instance method of [Waterfall
](#Waterfall)
+**Params**
-| Param | Type |
-| --- | --- |
-| promise | Promise
|
+- promise Promise
diff --git a/docs/customUtilsBrowser.md b/docs/customUtilsBrowser.md
index b0f6f31..3a931d0 100644
--- a/docs/customUtilsBrowser.md
+++ b/docs/customUtilsBrowser.md
@@ -17,10 +17,9 @@ https://github.com/dominictarr/crypto-browserify
NOTE: Math.random() does not guarantee "cryptographic quality" but we actually don't need it
**Kind**: inner method of [customUtilsBrowser
](#module_customUtilsBrowser)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| size | number
| in bytes
|
+- size number
- in bytes
@@ -29,8 +28,7 @@ NOTE: Math.random() does not guarantee "cryptographic quality" but we
https://github.com/beatgammit/base64-js/
**Kind**: inner method of [customUtilsBrowser
](#module_customUtilsBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| uint8 | array
|
+- uint8 array
diff --git a/docs/customUtilsNode.md b/docs/customUtilsNode.md
index 5c86017..ec23df5 100644
--- a/docs/customUtilsNode.md
+++ b/docs/customUtilsNode.md
@@ -20,10 +20,9 @@ The probability of a collision is extremely small (need 3*10^12 documents to hav
See http://en.wikipedia.org/wiki/Birthday_problem
**Kind**: static method of [customUtilsNode
](#module_customUtilsNode)
+**Params**
-| Param | Type |
-| --- | --- |
-| len | number
|
+- len number
@@ -36,8 +35,7 @@ The probability of a collision is extremely small (need 3*10^12 documents to hav
See http://en.wikipedia.org/wiki/Birthday_problem
**Kind**: static method of [customUtilsNode
](#module_customUtilsNode)
+**Params**
-| Param | Type |
-| --- | --- |
-| len | number
|
+- len number
diff --git a/docs/globals.md b/docs/globals.md
new file mode 100644
index 0000000..b1a8a76
--- /dev/null
+++ b/docs/globals.md
@@ -0,0 +1,155 @@
+
+
+## NoParamCallback : function
+Callback with no parameter
+
+**Kind**: global typedef
+**Params**
+
+- err Error
+
+
+
+
+## compareStrings ⇒ number
+String comparison function.
+ if (a < b) return -1
+ if (a > b) return 1
+ return 0
+
+
+**Kind**: global typedef
+**Params**
+
+- a string
+- b string
+
+
+
+
+## MultipleDocumentsCallback : function
+Callback that returns an Array of documents
+
+**Kind**: global typedef
+**Params**
+
+- err Error
+- docs [Array.<document>
](#document)
+
+
+
+
+## SingleDocumentCallback : function
+Callback that returns a single document
+
+**Kind**: global typedef
+**Params**
+
+- err Error
+- docs [document
](#document)
+
+
+
+
+## AsyncFunction ⇒ Promise.<\*>
+Generic async function
+
+**Kind**: global typedef
+**Params**
+
+- ...args \*
+
+
+
+
+## document : Object.<string, \*>
+Generic document in NeDB.
+It consists of an Object with anything you want inside.
+
+**Kind**: global typedef
+**Properties**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| [_id] | string
| Internal _id
of the document, which can be null
or undefined at some points (when not inserted yet for example).
|
+
+
+
+
+## query : Object.<string, \*>
+Nedb query.
+Each key of a query references a field name, which can use the dot-notation to reference subfields inside nested
+documents, arrays, arrays of subdocuments and to match a specific element of an array.
+Each value of a query can be one of the following:
+
+string
: matches all documents which have this string as value for the referenced field name
+number
: matches all documents which have this number as value for the referenced field name
+Regexp
: matches all documents which have a value that matches the given Regexp
for the referenced field name
+object
: matches all documents which have this object as deep-value for the referenced field name
+- Comparison operators: the syntax is
{ field: { $op: value } }
where $op
is any comparison operator:
+
+$lt
, $lte
: less than, less than or equal
+$gt
, $gte
: greater than, greater than or equal
+$in
: member of. value
must be an array of values
+$ne
, $nin
: not equal, not a member of
+$stat
: checks whether the document posses the property field
. value
should be true or false
+$regex
: checks whether a string is matched by the regular expression. Contrary to MongoDB, the use of
+$options
with $regex
is not supported, because it doesn't give you more power than regex flags. Basic
+queries are more readable so only use the $regex
operator when you need to use another operator with it
+$size
: if the referenced filed is an Array, matches on the size of the array
+$elemMatch
: matches if at least one array element matches the sub-query entirely
+
+
+- Logical operators: You can combine queries using logical operators:
+
+- For
$or
and $and
, the syntax is { $op: [query1, query2, ...] }
.
+- For
$not
, the syntax is { $not: query }
+- For
$where
, the syntax is:
+
+{ $where: function () {
+ // object is 'this'
+ // return a boolean
+} }
+
+
+
+
+**Kind**: global typedef
+
+
+
+## projection : Object.<string, (0\|1)>
+Nedb projection.
+You can give find
and findOne
an optional second argument, projections
.
+The syntax is the same as MongoDB: { a: 1, b: 1 }
to return only the a
+and b
fields, { a: 0, b: 0 }
to omit these two fields. You cannot use both
+modes at the time, except for _id
which is by default always returned and
+which you can choose to omit. You can project on nested documents.
+To reference subfields, you can use the dot-notation.
+
+**Kind**: global typedef
+
+
+
+## serializationHook ⇒ string
+The beforeDeserialization
and afterDeserialization
callbacks should
+
+**Kind**: global typedef
+**Params**
+
+- x string
+
+
+
+
+## rawIndex
+**Kind**: global typedef
+**Properties**
+
+| Name | Type |
+| --- | --- |
+| fieldName | string
|
+| [unique] | boolean
|
+| [sparse] | boolean
|
+
+
diff --git a/docs/model.md b/docs/model.md
index 3acaa33..5bd8153 100644
--- a/docs/model.md
+++ b/docs/model.md
@@ -32,10 +32,9 @@ Querying, update
Works by applying the above checkKey function to all fields recursively
**Kind**: static method of [model
](#module_model)
+**Params**
-| Param | Type |
-| --- | --- |
-| obj | [document
](#document) \| [Array.<document>
](#document) |
+- obj [document
](#document) | [Array.<document>
](#document)
@@ -48,10 +47,9 @@ Accepted primitive types: Number, String, Boolean, Date, null
Accepted secondary types: Objects, Arrays
**Kind**: static method of [model
](#module_model)
+**Params**
-| Param | Type |
-| --- | --- |
-| obj | [document
](#document) |
+- obj [document
](#document)
@@ -60,10 +58,9 @@ Accepted secondary types: Objects, Arrays
Return the object itself
**Kind**: static method of [model
](#module_model)
+**Params**
-| Param | Type |
-| --- | --- |
-| rawData | string
|
+- rawData string
@@ -76,12 +73,11 @@ If two objects dont have the same type, the (arbitrary) type hierarchy is: undef
Return -1 if a < b, 1 if a > b and 0 if a = b (note that equality here is NOT the same as defined in areThingsEqual!)
**Kind**: static method of [model
](#module_model)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| a | \*
| |
-| b | \*
| |
-| [_compareStrings] | [compareStrings
](#compareStrings) | String comparing function, returning -1, 0 or 1, overriding default string comparison (useful for languages with accented letters)
|
+- a \*
+- b \*
+- [_compareStrings] [compareStrings
](#compareStrings) - String comparing function, returning -1, 0 or 1, overriding default string comparison (useful for languages with accented letters)
@@ -89,11 +85,10 @@ Return -1 if a < b, 1 if a > b and 0 if a = b (note that equality here is
Modify a DB object according to an update query
**Kind**: static method of [model
](#module_model)
+**Params**
-| Param | Type |
-| --- | --- |
-| obj | [document
](#document) |
-| updateQuery | [query
](#query) |
+- obj [document
](#document)
+- updateQuery [query
](#query)
@@ -101,11 +96,10 @@ Return -1 if a < b, 1 if a > b and 0 if a = b (note that equality here is
Get a value from object with dot notation
**Kind**: static method of [model
](#module_model)
+**Params**
-| Param | Type |
-| --- | --- |
-| obj | object
|
-| field | string
|
+- obj object
+- field string
@@ -116,11 +110,10 @@ In the case of object, we check deep equality
Returns true if they are, false otherwise
**Kind**: static method of [model
](#module_model)
+**Params**
-| Param | Type |
-| --- | --- |
-| a | \*
|
-| a | \*
|
+- a \*
+- a \*
@@ -128,11 +121,10 @@ Returns true if they are, false otherwise
Tell if a given document matches a query
**Kind**: static method of [model
](#module_model)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| obj | [document
](#document) | Document to check
|
-| query | [query
](#query) | |
+- obj [document
](#document) - Document to check
+- query [query
](#query)
@@ -189,29 +181,26 @@ Returns true if they are, false otherwise
### model~modifierFunction : function
**Kind**: inner typedef of [model
](#module_model)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| obj | Object
| The model to modify
|
-| field | String
| Can contain dots, in that case that means we will set a subfield recursively
|
-| value | [document
](#document) | |
+- obj Object
- The model to modify
+- field String
- Can contain dots, in that case that means we will set a subfield recursively
+- value [document
](#document)
### model~comparisonOperator ⇒ boolean
**Kind**: inner typedef of [model
](#module_model)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| a | \*
| Value in the object
|
-| b | \*
| Value in the query
|
+- a \*
- Value in the object
+- b \*
- Value in the query
### model~whereCallback ⇒ boolean
**Kind**: inner typedef of [model
](#module_model)
+**Params**
-| Param | Type |
-| --- | --- |
-| obj | [document
](#document) |
+- obj [document
](#document)
diff --git a/docs/storage.md b/docs/storage.md
index dffd9d7..86d9525 100644
--- a/docs/storage.md
+++ b/docs/storage.md
@@ -1,12 +1,14 @@
## storage
-Way data is stored for this database
-For a Node.js/Node Webkit database it's the file system
-For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
-For a react-native database, we use @react-native-async-storage/async-storage
-This version is the Node.js/Node Webkit version
-It's essentially fs, mkdirp and crash safe write and read functions
+Way data is stored for this database.
+This version is the Node.js/Node Webkit version.
+It's essentially fs, mkdirp and crash safe write and read functions.
+
+**See**
+
+- module:storageBrowser
+- module:storageReactNative
* [storage](#module_storage)
@@ -31,7 +33,7 @@ It's essentially fs, mkdirp and crash safe write and read functions
* [.ensureFileDoesntExist(file, callback)](#module_storage.ensureFileDoesntExist)
* [.flushToStorage(options, callback)](#module_storage.flushToStorage)
* [.flushToStorageAsync(options)](#module_storage.flushToStorageAsync) ⇒ Promise.<void>
- * [.writeFileLines(filename, lines, callback)](#module_storage.writeFileLines)
+ * [.writeFileLines(filename, lines, [callback])](#module_storage.writeFileLines)
* [.writeFileLinesAsync(filename, lines)](#module_storage.writeFileLinesAsync) ⇒ Promise.<void>
* [.crashSafeWriteFileLines(filename, lines, [callback])](#module_storage.crashSafeWriteFileLines)
* [.crashSafeWriteFileLinesAsync(filename, lines)](#module_storage.crashSafeWriteFileLinesAsync) ⇒ Promise.<void>
@@ -43,327 +45,316 @@ It's essentially fs, mkdirp and crash safe write and read functions
### storage.exists(file, cb)
-Callback returns true if file exists
+Callback returns true if file exists.
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
-| cb | [existsCallback
](#module_storage..existsCallback) |
+- file string
+- cb [existsCallback
](#module_storage..existsCallback)
### storage.existsAsync(file) ⇒ Promise.<boolean>
-Returns Promise if file exists
+Async version of [exists](#module_storage.exists).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.exists
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
+- file string
### storage.rename(oldPath, newPath, c) ⇒ void
-Node.js' fs.rename
+Node.js' [fs.rename](https://nodejs.org/api/fs.html#fsrenameoldpath-newpath-callback).
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| oldPath | string
|
-| newPath | string
|
-| c | [NoParamCallback
](#NoParamCallback) |
+- oldPath string
+- newPath string
+- c [NoParamCallback
](#NoParamCallback)
### storage.renameAsync(oldPath, newPath) ⇒ Promise.<void>
-Node.js' fs.promises.rename
+Async version of [rename](#module_storage.rename).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.rename
+**Params**
-| Param | Type |
-| --- | --- |
-| oldPath | string
|
-| newPath | string
|
+- oldPath string
+- newPath string
### storage.writeFile(path, data, options, callback)
-Node.js' fs.writeFile
+Node.js' [fs.writeFile](https://nodejs.org/api/fs.html#fswritefilefile-data-options-callback).
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| data | string
|
-| options | object
|
-| callback | function
|
+- path string
+- data string
+- options object
+- callback function
### storage.writeFileAsync(path, data, [options]) ⇒ Promise.<void>
-Node.js' fs.promises.writeFile
+Async version of [writeFile](#module_storage.writeFile).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.writeFile
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| data | string
|
-| [options] | object
|
+- path string
+- data string
+- [options] object
### storage.writeFileStream(path, [options]) ⇒ fs.WriteStream
-Node.js' fs.createWriteStream
+Node.js' [fs.createWriteStream](https://nodejs.org/api/fs.html#fscreatewritestreampath-options).
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| [options] | Object
|
+- path string
+- [options] Object
### storage.unlink(path, callback)
-Node.js' fs.unlink
+Node.js' [fs.unlink](https://nodejs.org/api/fs.html#fsunlinkpath-callback).
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| callback | function
|
+- path string
+- callback function
### storage.unlinkAsync(path) ⇒ Promise.<void>
-Node.js' fs.promises.unlink
+Async version of [unlink](#module_storage.unlink).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.unlink
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
+- path string
### storage.appendFile(path, data, options, callback)
-Node.js' fs.appendFile
+Node.js' [fs.appendFile](https://nodejs.org/api/fs.html#fsappendfilepath-data-options-callback).
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| data | string
|
-| options | object
|
-| callback | function
|
+- path string
+- data string
+- options object
+- callback function
### storage.appendFileAsync(path, data, [options]) ⇒ Promise.<void>
-Node.js' fs.promises.appendFile
+Async version of [appendFile](#module_storage.appendFile).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.appendFile
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| data | string
|
-| [options] | object
|
+- path string
+- data string
+- [options] object
### storage.readFile(path, options, callback)
-Node.js' fs.readFile
+Node.js' [fs.readFile](https://nodejs.org/api/fs.html#fsreadfilepath-options-callback)
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| options | object
|
-| callback | function
|
+- path string
+- options object
+- callback function
### storage.readFileAsync(path, [options]) ⇒ Promise.<Buffer>
-Node.js' fs.promises.readFile
+Async version of [readFile](#module_storage.readFile).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.readFile
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| [options] | object
|
+- path string
+- [options] object
### storage.readFileStream(path, [options]) ⇒ fs.ReadStream
-Node.js' fs.createReadStream
+Node.js' [fs.createReadStream](https://nodejs.org/api/fs.html#fscreatereadstreampath-options).
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| [options] | Object
|
+- path string
+- [options] Object
### storage.mkdir(path, options, callback)
-Node.js' fs.mkdir
+Node.js' [fs.mkdir](https://nodejs.org/api/fs.html#fsmkdirpath-options-callback).
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| options | object
|
-| callback | function
|
+- path string
+- options object
+- callback function
### storage.mkdirAsync(path, options) ⇒ Promise.<(void\|string)>
-Node.js' fs.promises.mkdir
+Async version of [mkdir](#module_storage.mkdir).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.mkdir
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| options | object
|
+- path string
+- options object
### storage.ensureFileDoesntExistAsync(file) ⇒ Promise.<void>
+Async version of [ensureFileDoesntExist](#module_storage.ensureFileDoesntExist)
+
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.ensureFileDoesntExist
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
+- file string
### storage.ensureFileDoesntExist(file, callback)
+Removes file if it exists.
+
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
-| callback | [NoParamCallback
](#NoParamCallback) |
+- file string
+- callback [NoParamCallback
](#NoParamCallback)
### storage.flushToStorage(options, callback)
-Flush data in OS buffer to storage if corresponding option is set
+Flush data in OS buffer to storage if corresponding option is set.
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| options | object
\| string
| | If options is a string, it is assumed that the flush of the file (not dir) called options was requested
|
-| [options.filename] | string
| | |
-| [options.isDir] | boolean
| false
| Optional, defaults to false
|
-| callback | [NoParamCallback
](#NoParamCallback) | | |
+- options object
| string
- If options is a string, it is assumed that the flush of the file (not dir) called options was requested
+ - [.filename] string
+ - [.isDir] boolean
= false
- Optional, defaults to false
+- callback [NoParamCallback
](#NoParamCallback)
### storage.flushToStorageAsync(options) ⇒ Promise.<void>
-Flush data in OS buffer to storage if corresponding option is set
+Async version of [flushToStorage](#module_storage.flushToStorage).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.flushToStorage
+**Params**
-| Param | Type | Default | Description |
-| --- | --- | --- | --- |
-| options | object
\| string
| | If options is a string, it is assumed that the flush of the file (not dir) called options was requested
|
-| [options.filename] | string
| | |
-| [options.isDir] | boolean
| false
| Optional, defaults to false
|
+- options object
| string
+ - [.filename] string
+ - [.isDir] boolean
= false
-### storage.writeFileLines(filename, lines, callback)
-Fully write or rewrite the datafile
+### storage.writeFileLines(filename, lines, [callback])
+Fully write or rewrite the datafile.
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| lines | Array.<string>
|
-| callback | [NoParamCallback
](#NoParamCallback) |
+- filename string
+- lines Array.<string>
+- [callback] [NoParamCallback
](#NoParamCallback) = () => {}
### storage.writeFileLinesAsync(filename, lines) ⇒ Promise.<void>
-Fully write or rewrite the datafile
+Async version of [writeFileLines](#module_storage.writeFileLines).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.writeFileLines
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| lines | Array.<string>
|
+- filename string
+- lines Array.<string>
### storage.crashSafeWriteFileLines(filename, lines, [callback])
-Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost)
+Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost).
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| filename | string
| |
-| lines | Array.<string>
| |
-| [callback] | [NoParamCallback
](#NoParamCallback) | Optional callback, signature: err
|
+- filename string
+- lines Array.<string>
+- [callback] [NoParamCallback
](#NoParamCallback) - Optional callback, signature: err
### storage.crashSafeWriteFileLinesAsync(filename, lines) ⇒ Promise.<void>
-Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost)
+Async version of [crashSafeWriteFileLines](#module_storage.crashSafeWriteFileLines).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.crashSafeWriteFileLines
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| lines | Array.<string>
|
+- filename string
+- lines Array.<string>
### storage.ensureDatafileIntegrity(filename, callback)
-Ensure the datafile contains all the data, even if there was a crash during a full file write
+Ensure the datafile contains all the data, even if there was a crash during a full file write.
**Kind**: static method of [storage
](#module_storage)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| filename | string
| |
-| callback | [NoParamCallback
](#NoParamCallback) | signature: err
|
+- filename string
+- callback [NoParamCallback
](#NoParamCallback) - signature: err
### storage.ensureDatafileIntegrityAsync(filename) ⇒ Promise.<void>
-Ensure the datafile contains all the data, even if there was a crash during a full file write
+Async version of [ensureDatafileIntegrity](#module_storage.ensureDatafileIntegrity).
**Kind**: static method of [storage
](#module_storage)
+**See**: module:storage.ensureDatafileIntegrity
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
+- filename string
### storage~existsCallback : function
**Kind**: inner typedef of [storage
](#module_storage)
+**Params**
-| Param | Type |
-| --- | --- |
-| exists | boolean
|
+- exists boolean
diff --git a/docs/storageBrowser.md b/docs/storageBrowser.md
index e7d620c..343cdfe 100644
--- a/docs/storageBrowser.md
+++ b/docs/storageBrowser.md
@@ -1,10 +1,13 @@
## storageBrowser
-Way data is stored for this database
-For a Node.js/Node Webkit database it's the file system
-For a browser-side database it's localforage which chooses the best option depending on user browser (IndexedDB then WebSQL then localStorage)
-This version is the browser version
+Way data is stored for this database
+This version is the browser version and uses [localforage](https://github.com/localForage/localForage) which chooses the best option depending on user browser (IndexedDB then WebSQL then localStorage).
+
+**See**
+
+- module:storage
+- module:storageReactNative
* [storageBrowser](#module_storageBrowser)
@@ -33,37 +36,37 @@ For a browser-side database it's localforage which chooses the best option depen
### storageBrowser.existsAsync(file) ⇒ Promise.<boolean>
-Returns Promise if file exists
+Returns Promise if file exists.
+Async version of [exists](#module_storageBrowser.exists).
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**See**: module:storageBrowser.exists
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
+- file string
### storageBrowser.exists(file, cb)
-Callback returns true if file exists
+Callback returns true if file exists.
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
-| cb | [existsCallback
](#module_storageBrowser..existsCallback) |
+- file string
+- cb [existsCallback
](#module_storageBrowser..existsCallback)
### storageBrowser.renameAsync(oldPath, newPath) ⇒ Promise.<void>
-Moves the item from one path to another
+Async version of [rename](#module_storageBrowser.rename).
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**See**: module:storageBrowser.rename
+**Params**
-| Param | Type |
-| --- | --- |
-| oldPath | string
|
-| newPath | string
|
+- oldPath string
+- newPath string
@@ -71,25 +74,24 @@ For a browser-side database it's localforage which chooses the best option depen
Moves the item from one path to another
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| oldPath | string
|
-| newPath | string
|
-| c | [NoParamCallback
](#NoParamCallback) |
+- oldPath string
+- newPath string
+- c [NoParamCallback
](#NoParamCallback)
### storageBrowser.writeFileAsync(file, data, [options]) ⇒ Promise.<void>
-Saves the item at given path
+Async version of [writeFile](#module_storageBrowser.writeFile).
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**See**: module:storageBrowser.writeFile
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
-| data | string
|
-| [options] | object
|
+- file string
+- data string
+- [options] object
@@ -97,26 +99,25 @@ For a browser-side database it's localforage which chooses the best option depen
Saves the item at given path
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| data | string
|
-| options | object
|
-| callback | function
|
+- path string
+- data string
+- options object
+- callback function
### storageBrowser.appendFileAsync(filename, toAppend, [options]) ⇒ Promise.<void>
-Append to the item at given path
+Async version of [appendFile](#module_storageBrowser.appendFile).
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**See**: module:storageBrowser.appendFile
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| toAppend | string
|
-| [options] | object
|
+- filename string
+- toAppend string
+- [options] object
@@ -124,25 +125,24 @@ For a browser-side database it's localforage which chooses the best option depen
Append to the item at given path
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| toAppend | string
|
-| [options] | object
|
-| callback | function
|
+- filename string
+- toAppend string
+- [options] object
+- callback function
### storageBrowser.readFileAsync(filename, [options]) ⇒ Promise.<Buffer>
-Read data at given path
+Async version of [readFile](#module_storageBrowser.readFile).
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**See**: module:storageBrowser.readFile
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| [options] | object
|
+- filename string
+- [options] object
@@ -150,23 +150,22 @@ For a browser-side database it's localforage which chooses the best option depen
Read data at given path
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| options | object
|
-| callback | function
|
+- filename string
+- options object
+- callback function
### storageBrowser.unlinkAsync(filename) ⇒ Promise.<void>
-Remove the data at given path
+Async version of [unlink](#module_storageBrowser.unlink).
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**See**: module:storageBrowser.unlink
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
+- filename string
@@ -174,73 +173,66 @@ For a browser-side database it's localforage which chooses the best option depen
Remove the data at given path
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| callback | function
|
+- path string
+- callback function
### storageBrowser.mkdirAsync(path, [options]) ⇒ Promise.<(void\|string)>
-Shim for storage.mkdirAsync, nothing to do, no directories will be used on the browser
+Shim for [mkdirAsync](#module_storage.mkdirAsync), nothing to do, no directories will be used on the browser.
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| [options] | object
|
+- path string
+- [options] object
### storageBrowser.mkdir(path, options, callback)
-Shim for storage.mkdir, nothing to do, no directories will be used on the browser
+Shim for [mkdir](#module_storage.mkdir), nothing to do, no directories will be used on the browser.
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| options | object
|
-| callback | function
|
+- path string
+- options object
+- callback function
### storageBrowser.ensureDatafileIntegrityAsync(filename) ⇒ Promise.<void>
-Ensure the datafile contains all the data, even if there was a crash during a full file write
-Nothing to do, no data corruption possible in the browser
+Shim for [ensureDatafileIntegrityAsync](#module_storage.ensureDatafileIntegrityAsync), nothing to do, no data corruption possible in the browser.
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
+- filename string
### storageBrowser.ensureDatafileIntegrity(filename, callback)
-Ensure the datafile contains all the data, even if there was a crash during a full file write
-Nothing to do, no data corruption possible in the browser
+Shim for [ensureDatafileIntegrity](#module_storage.ensureDatafileIntegrity), nothing to do, no data corruption possible in the browser.
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| filename | string
| |
-| callback | [NoParamCallback
](#NoParamCallback) | signature: err
|
+- filename string
+- callback [NoParamCallback
](#NoParamCallback) - signature: err
### storageBrowser.crashSafeWriteFileLinesAsync(filename, lines) ⇒ Promise.<void>
-Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost)
+Async version of [crashSafeWriteFileLines](#module_storageBrowser.crashSafeWriteFileLines).
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**See**: module:storageBrowser.crashSafeWriteFileLines
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| lines | Array.<string>
|
+- filename string
+- lines Array.<string>
@@ -248,19 +240,17 @@ Nothing to do, no data corruption possible in the browser
Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost)
**Kind**: static method of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| filename | string
| |
-| lines | Array.<string>
| |
-| [callback] | [NoParamCallback
](#NoParamCallback) | Optional callback, signature: err
|
+- filename string
+- lines Array.<string>
+- [callback] [NoParamCallback
](#NoParamCallback) - Optional callback, signature: err
### storageBrowser~existsCallback : function
**Kind**: inner typedef of [storageBrowser
](#module_storageBrowser)
+**Params**
-| Param | Type |
-| --- | --- |
-| exists | boolean
|
+- exists boolean
diff --git a/docs/storageReactNative.md b/docs/storageReactNative.md
index 405e4b5..68dc403 100644
--- a/docs/storageReactNative.md
+++ b/docs/storageReactNative.md
@@ -1,11 +1,13 @@
## storageReactNative
-Way data is stored for this database
-For a Node.js/Node Webkit database it's the file system
-For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
-For a react-native database, we use @react-native-async-storage/async-storage
-This version is the react-native version
+Way data is stored for this database
+This version is the React-Native version and uses [@react-native-async-storage/async-storage](https://github.com/react-native-async-storage/async-storage).
+
+**See**
+
+- module:storageBrowser
+- module:storageReactNative
* [storageReactNative](#module_storageReactNative)
@@ -34,13 +36,13 @@ For a react-native database, we use @react-native-async-storage/async-storage
### storageReactNative.existsAsync(file) ⇒ Promise.<boolean>
-Returns Promise if file exists
+Async version of [exists](#module_storageReactNative.exists).
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**See**: module:storageReactNative.exists
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
+- file string
@@ -48,23 +50,22 @@ For a react-native database, we use @react-native-async-storage/async-storageCallback returns true if file exists
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
-| cb | [existsCallback
](#module_storageReactNative..existsCallback) |
+- file string
+- cb [existsCallback
](#module_storageReactNative..existsCallback)
### storageReactNative.renameAsync(oldPath, newPath) ⇒ Promise.<void>
-Moves the item from one path to another
+Async version of [rename](#module_storageReactNative.rename).
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**See**: module:storageReactNative.rename
+**Params**
-| Param | Type |
-| --- | --- |
-| oldPath | string
|
-| newPath | string
|
+- oldPath string
+- newPath string
@@ -72,25 +73,24 @@ For a react-native database, we use @react-native-async-storage/async-storageMoves the item from one path to another
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| oldPath | string
|
-| newPath | string
|
-| c | [NoParamCallback
](#NoParamCallback) |
+- oldPath string
+- newPath string
+- c [NoParamCallback
](#NoParamCallback)
### storageReactNative.writeFileAsync(file, data, [options]) ⇒ Promise.<void>
-Saves the item at given path
+Async version of [writeFile](#module_storageReactNative.writeFile).
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**See**: module:storageReactNative.writeFile
+**Params**
-| Param | Type |
-| --- | --- |
-| file | string
|
-| data | string
|
-| [options] | object
|
+- file string
+- data string
+- [options] object
@@ -98,26 +98,25 @@ For a react-native database, we use @react-native-async-storage/async-storageSaves the item at given path
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| data | string
|
-| options | object
|
-| callback | function
|
+- path string
+- data string
+- options object
+- callback function
### storageReactNative.appendFileAsync(filename, toAppend, [options]) ⇒ Promise.<void>
-Append to the item at given path
+Async version of [appendFile](#module_storageReactNative.appendFile).
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**See**: module:storageReactNative.appendFile
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| toAppend | string
|
-| [options] | object
|
+- filename string
+- toAppend string
+- [options] object
@@ -125,25 +124,24 @@ For a react-native database, we use @react-native-async-storage/async-storageAppend to the item at given path
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| toAppend | string
|
-| [options] | object
|
-| callback | function
|
+- filename string
+- toAppend string
+- [options] object
+- callback function
### storageReactNative.readFileAsync(filename, [options]) ⇒ Promise.<string>
-Read data at given path
+Async version of [readFile](#module_storageReactNative.readFile).
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**See**: module:storageReactNative.readFile
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| [options] | object
|
+- filename string
+- [options] object
@@ -151,23 +149,22 @@ For a react-native database, we use @react-native-async-storage/async-storageRead data at given path
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| options | object
|
-| callback | function
|
+- filename string
+- options object
+- callback function
### storageReactNative.unlinkAsync(filename) ⇒ Promise.<void>
-Remove the data at given path
+Async version of [unlink](#module_storageReactNative.unlink).
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**See**: module:storageReactNative.unlink
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
+- filename string
@@ -175,73 +172,66 @@ For a react-native database, we use @react-native-async-storage/async-storageRemove the data at given path
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| callback | function
|
+- path string
+- callback function
### storageReactNative.mkdirAsync(dir, [options]) ⇒ Promise.<(void\|string)>
-Shim for storage.mkdirAsync, nothing to do, no directories will be used on the browser
+Shim for [mkdirAsync](#module_storage.mkdirAsync), nothing to do, no directories will be used on the browser.
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| dir | string
|
-| [options] | object
|
+- dir string
+- [options] object
### storageReactNative.mkdir(path, options, callback)
-Shim for storage.mkdir, nothing to do, no directories will be used on the browser
+Shim for [mkdir](#module_storage.mkdir), nothing to do, no directories will be used on the browser.
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| path | string
|
-| options | object
|
-| callback | function
|
+- path string
+- options object
+- callback function
### storageReactNative.ensureDatafileIntegrityAsync(filename) ⇒ Promise.<void>
-Ensure the datafile contains all the data, even if there was a crash during a full file write
-Nothing to do, no data corruption possible in the browser
+Shim for [ensureDatafileIntegrityAsync](#module_storage.ensureDatafileIntegrityAsync), nothing to do, no data corruption possible in the browser.
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
+- filename string
### storageReactNative.ensureDatafileIntegrity(filename, callback)
-Ensure the datafile contains all the data, even if there was a crash during a full file write
-Nothing to do, no data corruption possible in the browser
+Shim for [ensureDatafileIntegrity](#module_storage.ensureDatafileIntegrity), nothing to do, no data corruption possible in the browser.
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| filename | string
| |
-| callback | [NoParamCallback
](#NoParamCallback) | signature: err
|
+- filename string
+- callback [NoParamCallback
](#NoParamCallback) - signature: err
### storageReactNative.crashSafeWriteFileLinesAsync(filename, lines) ⇒ Promise.<void>
-Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost)
+Async version of [crashSafeWriteFileLines](#module_storageReactNative.crashSafeWriteFileLines).
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**See**: module:storageReactNative.crashSafeWriteFileLines
+**Params**
-| Param | Type |
-| --- | --- |
-| filename | string
|
-| lines | Array.<string>
|
+- filename string
+- lines Array.<string>
@@ -249,19 +239,17 @@ Nothing to do, no data corruption possible in the browser
Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost)
**Kind**: static method of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| filename | string
| |
-| lines | Array.<string>
| |
-| [callback] | [NoParamCallback
](#NoParamCallback) | Optional callback, signature: err
|
+- filename string
+- lines Array.<string>
+- [callback] [NoParamCallback
](#NoParamCallback) - Optional callback, signature: err
### storageReactNative~existsCallback : function
**Kind**: inner typedef of [storageReactNative
](#module_storageReactNative)
+**Params**
-| Param | Type |
-| --- | --- |
-| exists | boolean
|
+- exists boolean
diff --git a/docs/utils.md b/docs/utils.md
index 11cd495..c04794b 100644
--- a/docs/utils.md
+++ b/docs/utils.md
@@ -18,50 +18,47 @@ This replaces the underscore dependency.
### utils.uniq(array, [iteratee]) ⇒ Array
Produces a duplicate-free version of the array, using === to test object equality. In particular only the first
occurrence of each value is kept. If you want to compute unique items based on a transformation, pass an iteratee
-function.
-Heavily inspired by https://underscorejs.org/#uniq
+function.
+Heavily inspired by [https://underscorejs.org/#uniq](https://underscorejs.org/#uniq).
**Kind**: static method of [utils
](#module_utils)
+**Params**
-| Param | Type | Description |
-| --- | --- | --- |
-| array | Array
| |
-| [iteratee] | function
| transformation applied to every element before checking for duplicates. This will not transform the items in the result.
|
+- array Array
+- [iteratee] function
- transformation applied to every element before checking for duplicates. This will not
+transform the items in the result.
### utils.isDate(d) ⇒ boolean
-Returns true if d is a Date.
-Heavily inspired by https://underscorejs.org/#isDate
+Returns true if d is a Date.
+Heavily inspired by [https://underscorejs.org/#isDate](https://underscorejs.org/#isDate).
**Kind**: static method of [utils
](#module_utils)
+**Params**
-| Param | Type |
-| --- | --- |
-| d | \*
|
+- d \*
### utils.isRegExp(re) ⇒ boolean
-Returns true if re is a RegExp.
-Heavily inspired by https://underscorejs.org/#isRegExp
+Returns true if re is a RegExp.
+Heavily inspired by [https://underscorejs.org/#isRegExp](https://underscorejs.org/#isRegExp).
**Kind**: static method of [utils
](#module_utils)
+**Params**
-| Param | Type |
-| --- | --- |
-| re | \*
|
+- re \*
### utils~isObject(arg) ⇒ boolean
Returns true if arg is an Object. Note that JavaScript arrays and functions are objects, while (normal) strings
-and numbers are not.
-Heavily inspired by https://underscorejs.org/#isObject
+and numbers are not.
+Heavily inspired by [https://underscorejs.org/#isObject](https://underscorejs.org/#isObject).
**Kind**: inner method of [utils
](#module_utils)
+**Params**
-| Param | Type |
-| --- | --- |
-| arg | \*
|
+- arg \*
diff --git a/jsdoc2md.js b/jsdoc2md.js
index dea093c..a122382 100644
--- a/jsdoc2md.js
+++ b/jsdoc2md.js
@@ -15,6 +15,10 @@ const getJsdocDataOptions = {
'no-cache': true
}
+const renderOptions = {
+ 'param-list-format': 'list'
+}
+
fs.rmdirSync(outputDir, { recursive: true }) // clean docs dir
fs.mkdirSync(outputDir) // make docs dir
@@ -22,15 +26,24 @@ fs.mkdirSync(outputDir) // make docs dir
const templateData = jsdoc2md.getTemplateDataSync(getJsdocDataOptions)
/* reduce templateData to an array of class names */
-const classNames = templateData.filter(({ kind }) => kind === 'class').map(({ name }) => name)
+const classNames = templateData
+ .filter(({ kind, access }) => kind === 'class' && access !== 'private')
+ .map(({ name }) => name)
+
+const moduleNames = templateData
+ .filter(({ kind, access }) => kind === 'module' && access !== 'private')
+ .map(({ name }) => name)
-const moduleNames = templateData.filter(({ kind }) => kind === 'module').map(({ name }) => name)
+const rest = templateData
+ .filter(({ name }) => !moduleNames.includes(name) && !classNames.includes(name))
+ .filter(({ scope, access }) => scope === 'global' && access !== 'private')
+ .map(({ id }) => id)
/* create a documentation file for each class */
for (const className of classNames) {
const template = `{{#class name="${className}"}}{{>docs}}{{/class}}`
console.log(`rendering ${className}, template: ${template}`)
- const output = jsdoc2md.renderSync({ data: templateData, template: template })
+ const output = jsdoc2md.renderSync({ ...renderOptions, data: templateData, template: template })
fs.writeFileSync(path.resolve(outputDir, `${className}.md`), output)
}
@@ -38,6 +51,16 @@ for (const className of classNames) {
for (const moduleName of moduleNames) {
const template = `{{#module name="${moduleName}"}}{{>docs}}{{/module}}`
console.log(`rendering ${moduleName}, template: ${template}`)
- const output = jsdoc2md.renderSync({ data: templateData, template: template })
+ const output = jsdoc2md.renderSync({ ...renderOptions, data: templateData, template: template })
fs.writeFileSync(path.resolve(outputDir, `${moduleName}.md`), output)
}
+
+let template = ''
+for (const id of rest) {
+ template += `{{#identifier name="${id}"}}{{>docs}}{{/identifier}}\n`
+}
+console.log(`rendering globals, template: ${template}`)
+const output = jsdoc2md.renderSync({ ...renderOptions, data: templateData, template: template })
+fs.writeFileSync(path.resolve(outputDir, 'globals.md'), output)
+
+// TODO rewrite links between files
diff --git a/lib/cursor.js b/lib/cursor.js
index 4e8cfe0..e5f4f72 100755
--- a/lib/cursor.js
+++ b/lib/cursor.js
@@ -2,21 +2,23 @@ const model = require('./model.js')
const { callbackify, promisify } = require('util')
/**
- * @callback Cursor~execFn
+ * Has a callback
+ * @callback Cursor~execFnWithCallback
* @param {?Error} err
* @param {?document[]|?document} res
*/
/**
- * @callback Cursor~execFnAsync
+ * Does not have a callback, may return a Promise.
+ * @callback Cursor~execFnWithoutCallback
* @param {?document[]|?document} res
- * @return {Promise}
+ * @return {Promise|*}
*/
/**
* Manage access to data, be it to find, update or remove it.
*
- * It extends Promise so that its methods are chainable & awaitable.
+ * It extends `Promise` so that its methods (which return `this`) are chainable & awaitable.
* @extends Promise
*/
class Cursor {
@@ -24,18 +26,55 @@ class Cursor {
* Create a new cursor for this collection
* @param {Datastore} db - The datastore this cursor is bound to
* @param {query} query - The query this cursor will operate on
- * @param {Cursor~execFn|Cursor~execFnAsync} [execFn] - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove
- * @param {boolean} [async = false] If true, specifies that the `execFn` is of type {@link Cursor~execFnAsync} rather than {@link Cursor~execFn}.
- *
+ * @param {Cursor~execFnWithoutCallback|Cursor~execFnWithCallback} [execFn] - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove
+ * @param {boolean} [hasCallback = true] If false, specifies that the `execFn` is of type {@link Cursor~execFnWithoutCallback} rather than {@link Cursor~execFnWithCallback}.
*/
- constructor (db, query, execFn, async = false) {
+ constructor (db, query, execFn, hasCallback = true) {
+ /**
+ * @protected
+ * @type {Datastore}
+ */
this.db = db
+ /**
+ * @protected
+ * @type {query}
+ */
this.query = query || {}
+ /**
+ * The handler to be executed after cursor has found the results.
+ * @type {Cursor~execFnWithoutCallback|Cursor~execFnWithCallback|undefined}
+ * @protected
+ */
if (execFn) this.execFn = execFn
- if (async) this.async = true
+ /**
+ * Determines if the {@link Cursor#execFn} is an {@link Cursor~execFnWithoutCallback} or not.
+ * @protected
+ * @type {boolean}
+ */
+ this.hasCallback = hasCallback
+ /**
+ * @see Cursor#limit
+ * @type {undefined|number}
+ * @private
+ */
this._limit = undefined
+ /**
+ * @see Cursor#skip
+ * @type {undefined|number}
+ * @private
+ */
this._skip = undefined
+ /**
+ * @see Cursor#sort
+ * @type {undefined|Object.}
+ * @private
+ */
this._sort = undefined
+ /**
+ * @see Cursor#projection
+ * @type {undefined|Object.}
+ * @private
+ */
this._projection = undefined
}
@@ -81,9 +120,12 @@ class Cursor {
}
/**
- * Apply the projection
+ * Apply the projection.
+ *
+ * This is an internal function. You should use {@link Cursor#execAsync} or {@link Cursor#exec}.
* @param {document[]} candidates
* @return {document[]}
+ * @protected
*/
project (candidates) {
const res = []
@@ -185,7 +227,7 @@ class Cursor {
} catch (e) {
error = e
}
- if (this.execFn && !this.async) return promisify(this.execFn)(error, res)
+ if (this.execFn && this.hasCallback) return promisify(this.execFn)(error, res)
else if (error) throw error
else if (this.execFn) return this.execFn(res)
else return res
@@ -200,8 +242,11 @@ class Cursor {
/**
* Get all matching elements
* Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne
- * This is an internal function, use exec which uses the executor
- * @param { Cursor~execCallback} _callback
+ *
+ * This is an internal function, use {@link Cursor#exec} which uses the [executor]{@link Datastore#executor}.
+ * @param {Cursor~execCallback} _callback
+ * @protected
+ * @see Cursor#exec
*/
_exec (_callback) {
callbackify(this._execAsync.bind(this))(_callback)
@@ -210,17 +255,17 @@ class Cursor {
/**
* Get all matching elements
* Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne
- * @param { Cursor~execCallback} _callback
+ * @param {Cursor~execCallback} _callback
*/
exec (_callback) {
this.db.executor.push({ this: this, fn: this._exec, arguments: [_callback] })
}
/**
- * Get all matching elements
- * Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne
+ * Async version of {@link Cursor#exec}.
* @return {Promise}
* @async
+ * @see Cursor#exec
*/
execAsync () {
return this.db.executor.pushAsync(() => this._execAsync())
diff --git a/lib/datastore.js b/lib/datastore.js
index 7ff6050..63e4a71 100755
--- a/lib/datastore.js
+++ b/lib/datastore.js
@@ -53,7 +53,7 @@ const { isDate } = require('./utils.js')
* It happens when calling `datastore.persistence.compactDatafile`, which is called periodically if you have called
* `datastore.persistence.setAutocompactionInterval`.
*
- * @event Datastore.event:"compaction.done"
+ * @event Datastore#event:"compaction.done"
* @type {undefined}
*/
@@ -175,7 +175,7 @@ class Datastore extends EventEmitter {
* OS X and Windows. Now that you can use `require('nw.gui').App.dataPath` in Node Webkit to get the path to the data
* directory for your application, you should not use this option anymore and it will be removed.
*
- * @fires Datastore.event:"compaction.done"
+ * @fires Datastore#event:"compaction.done"
*/
constructor (options) {
super()
@@ -194,19 +194,19 @@ class Datastore extends EventEmitter {
* Determines if the `Datastore` keeps data in-memory, or if it saves it in storage. Is not read after
* instanciation.
* @type {boolean}
- * @private
+ * @protected
*/
this.inMemoryOnly = options.inMemoryOnly || false
/**
* Determines if the `Datastore` should autoload the database upon instantiation. Is not read after instanciation.
* @type {boolean}
- * @private
+ * @protected
*/
this.autoload = options.autoload || false
/**
* Determines if the `Datastore` should add `createdAt` and `updatedAt` fields automatically if not set by the user.
* @type {boolean}
- * @private
+ * @protected
*/
this.timestampData = options.timestampData || false
}
@@ -217,7 +217,7 @@ class Datastore extends EventEmitter {
* If null, it means `inMemoryOnly` is `true`. The `filename` is the name given to the storage module. Is not read
* after instanciation.
* @type {?string}
- * @private
+ * @protected
*/
this.filename = null
this.inMemoryOnly = true
@@ -230,7 +230,8 @@ class Datastore extends EventEmitter {
* Overrides default string comparison which is not well adapted to non-US characters in particular accented
* letters. Native `localCompare` will most of the time be the right choice
* @type {compareStrings}
- * @private
+ * @function
+ * @protected
*/
this.compareStrings = options.compareStrings
@@ -254,6 +255,7 @@ class Datastore extends EventEmitter {
* produced by the `Datastore` and by `this.persistence.compactDataFile` & `this.persistence.compactDataFileAsync`
* to ensure operations are performed sequentially in the database.
* @type {Executor}
+ * @protected
*/
this.executor = new Executor()
if (this.inMemoryOnly) this.executor.ready = true
@@ -262,7 +264,7 @@ class Datastore extends EventEmitter {
* Indexed by field name, dot notation can be used.
* _id is always indexed and since _ids are generated randomly the underlying binary search tree is always well-balanced
* @type {Object.}
- * @private
+ * @protected
*/
this.indexes = {}
this.indexes._id = new Index({ fieldName: '_id', unique: true })
@@ -270,7 +272,7 @@ class Datastore extends EventEmitter {
* Stores the time to live (TTL) of the indexes created. The key represents the field name, the value the number of
* seconds after which data with this index field should be removed.
* @type {Object.}
- * @private
+ * @protected
*/
this.ttlIndexes = {}
@@ -303,16 +305,17 @@ class Datastore extends EventEmitter {
}
/**
- * Load the database from the datafile, and trigger the execution of buffered commands if any.
+ * Async version of {@link Datastore#loadDatabase}.
* @async
* @return {Promise}
+ * @see Datastore#loadDatabase
*/
loadDatabaseAsync () {
return this.executor.pushAsync(() => this.persistence.loadDatabaseAsync(), true)
}
/**
- * Get an array of all the data in the database
+ * Get an array of all the data in the database.
* @return {document[]}
*/
getAllData () {
@@ -320,7 +323,8 @@ class Datastore extends EventEmitter {
}
/**
- * Reset all currently defined indexes
+ * Reset all currently defined indexes.
+ * @param {?document|?document[]} newData
*/
resetIndexes (newData) {
for (const index of Object.values(this.indexes)) {
@@ -346,16 +350,14 @@ class Datastore extends EventEmitter {
}
/**
- * Ensure an index is kept for this field. Same parameters as lib/indexes
- * This function acts synchronously on the indexes, however the persistence of the indexes is deferred with the
- * executor.
- * Previous versions said explicitly the callback was optional, it is now recommended setting one.
+ * Async version of {@link Datastore#ensureIndex}.
* @param {object} options
* @param {string} options.fieldName Name of the field to index. Use the dot notation to index a field in a nested document.
* @param {boolean} [options.unique = false] Enforce field uniqueness. Note that a unique index will raise an error if you try to index two documents for which the field is not defined.
* @param {boolean} [options.sparse = false] Don't index documents for which the field is not defined. Use this option along with "unique" if you want to accept multiple documents for which it is not defined.
* @param {number} [options.expireAfterSeconds] - If set, the created index is a TTL (time to live) index, that will automatically remove documents when the system date becomes larger than the date on the indexed field plus `expireAfterSeconds`. Documents where the indexed field is not specified or not a `Date` object are ignored
* @return {Promise}
+ * @see Datastore#ensureIndex
*/
// TODO: contrary to what is said in the JSDoc, this function should probably be called through the executor, it persists a new state
async ensureIndexAsync (options = {}) {
@@ -393,11 +395,11 @@ class Datastore extends EventEmitter {
}
/**
- * Remove an index
- * Previous versions said explicitly the callback was optional, it is now recommended setting one.
+ * Async version of {@link Datastore#removeIndex}.
* @param {string} fieldName Field name of the index to remove. Use the dot notation to remove an index referring to a
* field in a nested document.
* @return {Promise}
+ * @see Datastore#removeIndex
*/
// TODO: contrary to what is said in the JSDoc, this function should probably be called through the executor, it persists a new state
async removeIndexAsync (fieldName) {
@@ -407,9 +409,11 @@ class Datastore extends EventEmitter {
}
/**
- * Add one or several document(s) to all indexes
+ * Add one or several document(s) to all indexes.
+ *
+ * This is an internal function.
* @param {document} doc
- * @private
+ * @protected
*/
addToIndexes (doc) {
let failingIndex
@@ -437,8 +441,11 @@ class Datastore extends EventEmitter {
}
/**
- * Remove one or several document(s) from all indexes
+ * Remove one or several document(s) from all indexes.
+ *
+ * This is an internal function.
* @param {document} doc
+ * @protected
*/
removeFromIndexes (doc) {
for (const index of Object.values(this.indexes)) {
@@ -447,9 +454,13 @@ class Datastore extends EventEmitter {
}
/**
- * Update one or several documents in all indexes
- * To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs
- * If one update violates a constraint, all changes are rolled back
+ * Update one or several documents in all indexes.
+ *
+ * To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs.
+ *
+ * If one update violates a constraint, all changes are rolled back.
+ *
+ * This is an internal function.
* @param {document|Array.<{oldDoc: document, newDoc: document}>} oldDoc Document to update, or an `Array` of
* `{oldDoc, newDoc}` pairs.
* @param {document} [newDoc] Document to replace the oldDoc with. If the first argument is an `Array` of
@@ -528,12 +539,13 @@ class Datastore extends EventEmitter {
*
* Returned candidates will be scanned to find and remove all expired documents
*
+ * This is an internal function.
* @param {query} query
* @param {boolean|function} [dontExpireStaleDocs = false] If true don't remove stale docs. Useful for the remove
* function which shouldn't be impacted by expirations. If argument is not given, it is used as the callback.
* @param {MultipleDocumentsCallback} callback Signature err, candidates
*
- * @private
+ * @protected
*/
getCandidates (query, dontExpireStaleDocs, callback) {
if (typeof dontExpireStaleDocs === 'function') {
@@ -545,20 +557,15 @@ class Datastore extends EventEmitter {
}
/**
- * Return the list of candidates for a given query
- * Crude implementation for now, we return the candidates given by the first usable index if any
- * We try the following query types, in this order: basic match, $in match, comparison match
- * One way to make it better would be to enable the use of multiple indexes if the first usable index
- * returns too much data. I may do it in the future.
- *
- * Returned candidates will be scanned to find and remove all expired documents
+ * Async version of {@link Datastore#getCandidates}.
*
+ * This is an internal function.
* @param {query} query
* @param {boolean} [dontExpireStaleDocs = false] If true don't remove stale docs. Useful for the remove function
* which shouldn't be impacted by expirations.
* @return {Promise} candidates
- *
- * @private
+ * @see Datastore#getCandidates
+ * @protected
*/
async getCandidatesAsync (query, dontExpireStaleDocs = false) {
const validDocs = []
@@ -583,22 +590,22 @@ class Datastore extends EventEmitter {
/**
* Insert a new document
- * Private Use Datastore.insert which has the same signature
+ * This is an internal function, use {@link Datastore#insert} which has the same signature.
* @param {document|document[]} newDoc
- * @param {SingleDocumentCallback} [callback = () => {}] Optional callback, signature: err, insertedDoc
+ * @param {SingleDocumentCallback} callback
*
* @private
*/
- _insert (newDoc, callback = () => {}) {
+ _insert (newDoc, callback) {
return callbackify(this._insertAsync.bind(this))(newDoc, callback)
}
/**
- * Insert a new document
- * Private Use Datastore.insertAsync which has the same signature
+ * Async version of {@link Datastore#_insert}.
* @param {document|document[]} newDoc
* @return {Promise}
* @private
+ * @see Datastore#_insert
*/
async _insertAsync (newDoc) {
const preparedDoc = this._prepareDocumentForInsertion(newDoc)
@@ -685,26 +692,24 @@ class Datastore extends EventEmitter {
}
/**
- * Insert a new document
- * Private Use Datastore.insert which has the same signature
+ * Insert a new document.
* @param {document|document[]} newDoc
* @param {SingleDocumentCallback} [callback = () => {}] Optional callback, signature: err, insertedDoc
*
* @private
*/
- insert (...args) {
- this.executor.push({ this: this, fn: this._insert, arguments: args })
+ insert (newDoc, callback = () => {}) {
+ this.executor.push({ this: this, fn: this._insert, arguments: [newDoc, callback] })
}
/**
- * Insert a new document
- * Private Use Datastore.insertAsync which has the same signature
+ * Async version of {@link Datastore#insert}.
* @param {document|document[]} newDoc
* @return {Promise}
* @async
*/
- insertAsync (...args) {
- return this.executor.pushAsync(() => this._insertAsync(...args))
+ insertAsync (newDoc) {
+ return this.executor.pushAsync(() => this._insertAsync(newDoc))
}
/**
@@ -714,7 +719,7 @@ class Datastore extends EventEmitter {
*/
/**
- * Count all documents matching the query
+ * Count all documents matching the query.
* @param {query} query MongoDB-style query
* @param {Datastore~countCallback} [callback] If given, the function will return undefined, otherwise it will return the Cursor.
* @return {Cursor|undefined}
@@ -727,13 +732,13 @@ class Datastore extends EventEmitter {
}
/**
- * Count all documents matching the query
+ * Async version of {@link Datastore#count}.
* @param {query} query MongoDB-style query
* @return {Cursor} count
* @async
*/
countAsync (query) {
- return new Cursor(this, query, async docs => docs.length, true) // this is a trick, Cursor itself is a thenable, which allows to await it
+ return new Cursor(this, query, async docs => docs.length, false)
}
/**
@@ -763,15 +768,14 @@ class Datastore extends EventEmitter {
}
/**
- * Find all documents matching the query
- * If no callback is passed, we return the cursor so that user can limit, skip and finally exec
+ * Async version of {@link Datastore#find}.
* @param {query} query MongoDB-style query
* @param {projection} [projection = {}] MongoDB-style projection
* @return {Cursor}
* @async
*/
findAsync (query, projection = {}) {
- const cursor = new Cursor(this, query, docs => docs.map(doc => model.deepCopy(doc)), true)
+ const cursor = new Cursor(this, query, docs => docs.map(doc => model.deepCopy(doc)), false)
cursor.projection(projection)
return cursor
@@ -784,10 +788,10 @@ class Datastore extends EventEmitter {
*/
/**
- * Find one document matching the query
+ * Find one document matching the query.
* @param {query} query MongoDB-style query
- * @param {projection} projection MongoDB-style projection
- * @param {SingleDocumentCallback} callback Optional callback, signature: err, doc
+ * @param {projection|SingleDocumentCallback} [projection = {}] MongoDB-style projection
+ * @param {SingleDocumentCallback} [callback] Optional callback, signature: err, doc
* @return {Cursor|undefined}
*/
findOne (query, projection, callback) {
@@ -808,13 +812,14 @@ class Datastore extends EventEmitter {
}
/**
- * Find one document matching the query
+ * Async version of {@link Datastore#findOne}.
* @param {query} query MongoDB-style query
* @param {projection} projection MongoDB-style projection
* @return {Cursor}
+ * @see Datastore#findOne
*/
findOneAsync (query, projection = {}) {
- const cursor = new Cursor(this, query, docs => docs.length === 1 ? model.deepCopy(docs[0]) : null, true)
+ const cursor = new Cursor(this, query, docs => docs.length === 1 ? model.deepCopy(docs[0]) : null, false)
cursor.projection(projection).limit(1)
return cursor
@@ -843,7 +848,8 @@ class Datastore extends EventEmitter {
/**
* Update all docs matching query.
- * Use Datastore.update which has the same signature
+ *
+ * Use {@link Datastore#update} which has the same signature.
* @param {query} query is the same kind of finding query you use with `find` and `findOne`
* @param {document|update} update specifies how the documents should be modified. It is either a new document or a
* set of modifiers (you cannot use both together, it doesn't make sense!):
@@ -852,7 +858,7 @@ class Datastore extends EventEmitter {
* Available field modifiers are `$set` to change a field's value, `$unset` to delete a field, `$inc` to increment a
* field's value and `$min`/`$max` to change field's value, only if provided value is less/greater than current
* value. To work on arrays, you have `$push`, `$pop`, `$addToSet`, `$pull`, and the special `$each` and `$slice`.
- * @param {object|Datastore~updateCallback} [options] Optional options. If not given, is interpreted as the callback.
+ * @param {object} [options] Optional options. If not given, is interpreted as the callback.
* @param {boolean} [options.multi = false] If true, can update multiple documents
* @param {boolean} [options.upsert = false] If true, can insert a new document corresponding to the `update` rules if
* your `query` doesn't match anything. If your `update` is a simple object with no modifiers, it is the inserted
@@ -861,17 +867,11 @@ class Datastore extends EventEmitter {
* @param {boolean} [options.returnUpdatedDocs = false] (not Mongo-DB compatible) If true and update is not an upsert,
* will return the array of documents matched by the find query and updated. Updated documents will be returned even
* if the update did not actually modify them.
- * @param {Datastore~updateCallback} [cb = () => {}] Optional callback
+ * @param {Datastore~updateCallback} callback
*
* @private
*/
- _update (query, update, options, cb) {
- if (typeof options === 'function') {
- cb = options
- options = {}
- }
- const callback = cb || (() => {})
-
+ _update (query, update, options, callback) {
const _callback = (err, res = {}) => {
callback(err, res.numAffected, res.affectedDocuments, res.upsert)
}
@@ -879,8 +879,9 @@ class Datastore extends EventEmitter {
}
/**
- * Update all docs matching query.
- * Use Datastore.updateAsync which has the same signature
+ * Async version of {@link Datastore#_update}.
+ *
+ * Use {@link Datastore#updateAsync} which has the same signature.
* @param {query} query is the same kind of finding query you use with `find` and `findOne`
* @param {document|update} update specifies how the documents should be modified. It is either a new document or a
* set of modifiers (you cannot use both together, it doesn't make sense!):
@@ -889,7 +890,7 @@ class Datastore extends EventEmitter {
* Available field modifiers are `$set` to change a field's value, `$unset` to delete a field, `$inc` to increment a
* field's value and `$min`/`$max` to change field's value, only if provided value is less/greater than current
* value. To work on arrays, you have `$push`, `$pop`, `$addToSet`, `$pull`, and the special `$each` and `$slice`.
- * @param {Object} [options] Optional options
+ * @param {Object} options options
* @param {boolean} [options.multi = false] If true, can update multiple documents
* @param {boolean} [options.upsert = false] If true, can insert a new document corresponding to the `update` rules if
* your `query` doesn't match anything. If your `update` is a simple object with no modifiers, it is the inserted
@@ -900,16 +901,16 @@ class Datastore extends EventEmitter {
* if the update did not actually modify them.
*
* @return {Promise<{numAffected: number, affectedDocuments: document[]|document|null, upsert: boolean}>}
- *
+ * @see Datastore#_update
* @private
*/
- async _updateAsync (query, update, options = {}) {
+ async _updateAsync (query, update, options) {
const multi = options.multi !== undefined ? options.multi : false
const upsert = options.upsert !== undefined ? options.upsert : false
// If upsert option is set, check whether we need to insert the doc
if (upsert) {
- const cursor = new Cursor(this, query, x => x, true)
+ const cursor = new Cursor(this, query, x => x, false)
// Need to use an internal function not tied to the executor to avoid deadlock
const docs = await cursor.limit(1)._execAsync()
@@ -970,14 +971,14 @@ class Datastore extends EventEmitter {
/**
* Update all docs matching query.
* @param {query} query is the same kind of finding query you use with `find` and `findOne`
- * @param {document|update} update specifies how the documents should be modified. It is either a new document or a
+ * @param {document|*} update specifies how the documents should be modified. It is either a new document or a
* set of modifiers (you cannot use both together, it doesn't make sense!):
* - A new document will replace the matched docs
* - The modifiers create the fields they need to modify if they don't exist, and you can apply them to subdocs.
* Available field modifiers are `$set` to change a field's value, `$unset` to delete a field, `$inc` to increment a
* field's value and `$min`/`$max` to change field's value, only if provided value is less/greater than current
* value. To work on arrays, you have `$push`, `$pop`, `$addToSet`, `$pull`, and the special `$each` and `$slice`.
- * @param {Object} [options] Optional options
+ * @param {Object|Datastore~updateCallback} [options|] Optional options
* @param {boolean} [options.multi = false] If true, can update multiple documents
* @param {boolean} [options.upsert = false] If true, can insert a new document corresponding to the `update` rules if
* your `query` doesn't match anything. If your `update` is a simple object with no modifiers, it is the inserted
@@ -989,21 +990,26 @@ class Datastore extends EventEmitter {
* @param {Datastore~updateCallback} [cb = () => {}] Optional callback
*
*/
- update (...args) {
- this.executor.push({ this: this, fn: this._update, arguments: args })
+ update (query, update, options, cb) {
+ if (typeof options === 'function') {
+ cb = options
+ options = {}
+ }
+ const callback = cb || (() => {})
+ this.executor.push({ this: this, fn: this._update, arguments: [query, update, options, callback] })
}
/**
- * Update all docs matching query.
+ * Async version of {@link Datastore#update}.
* @param {query} query is the same kind of finding query you use with `find` and `findOne`
- * @param {document|update} update specifies how the documents should be modified. It is either a new document or a
+ * @param {document|*} update specifies how the documents should be modified. It is either a new document or a
* set of modifiers (you cannot use both together, it doesn't make sense!):
* - A new document will replace the matched docs
* - The modifiers create the fields they need to modify if they don't exist, and you can apply them to subdocs.
* Available field modifiers are `$set` to change a field's value, `$unset` to delete a field, `$inc` to increment a
* field's value and `$min`/`$max` to change field's value, only if provided value is less/greater than current
* value. To work on arrays, you have `$push`, `$pop`, `$addToSet`, `$pull`, and the special `$each` and `$slice`.
- * @param {Object} [options] Optional options
+ * @param {Object} [options = {}] Optional options
* @param {boolean} [options.multi = false] If true, can update multiple documents
* @param {boolean} [options.upsert = false] If true, can insert a new document corresponding to the `update` rules if
* your `query` doesn't match anything. If your `update` is a simple object with no modifiers, it is the inserted
@@ -1014,9 +1020,10 @@ class Datastore extends EventEmitter {
* if the update did not actually modify them.
* @async
* @return {Promise<{numAffected: number, affectedDocuments: document[]|document|null, upsert: boolean}>}
+ * @see Datastore#update
*/
- updateAsync (...args) {
- return this.executor.pushAsync(() => this._updateAsync(...args))
+ updateAsync (query, update, options = {}) {
+ return this.executor.pushAsync(() => this._updateAsync(query, update, options))
}
/**
@@ -1027,33 +1034,31 @@ class Datastore extends EventEmitter {
/**
* Remove all docs matching the query.
- * Use Datastore.remove which has the same signature
- * For now very naive implementation (similar to update)
+ *
+ * Use {@link Datastore#remove} which has the same signature.
+ *
+ * For now very naive implementation (similar to update).
* @param {query} query
- * @param {object} [options] Optional options
+ * @param {object} options options
* @param {boolean} [options.multi = false] If true, can update multiple documents
- * @param {Datastore~removeCallback} [cb = () => {}]
- *
+ * @param {Datastore~removeCallback} callback
+ * @see Datastore#remove
* @private
*/
- _remove (query, options, cb) {
- if (typeof options === 'function') {
- cb = options
- options = {}
- }
- const callback = cb || (() => {})
-
+ _remove (query, options, callback) {
callbackify(this._removeAsync.bind(this))(query, options, callback)
}
/**
- * Remove all docs matching the query.
- * Use Datastore.removeAsync which has the same signature
+ * Async version of {@link Datastore#_remove}.
+ *
+ * Use {@link Datastore#removeAsync} which has the same signature.
* @param {query} query
* @param {object} [options] Optional options
* @param {boolean} [options.multi = false] If true, can update multiple documents
* @return {Promise} How many documents were removed
* @private
+ * @see Datastore#_remove
*/
async _removeAsync (query, options = {}) {
const multi = options.multi !== undefined ? options.multi : false
@@ -1077,25 +1082,30 @@ class Datastore extends EventEmitter {
/**
* Remove all docs matching the query.
* @param {query} query
- * @param {object} [options] Optional options
+ * @param {object|Datastore~removeCallback} [options={}] Optional options
* @param {boolean} [options.multi = false] If true, can update multiple documents
- * @param {Datastore~removeCallback} [cb = () => {}] Optional callback, signature: err, numRemoved
+ * @param {Datastore~removeCallback} [cb = () => {}] Optional callback
*/
- remove (...args) {
- this.executor.push({ this: this, fn: this._remove, arguments: args })
+ remove (query, options, cb) {
+ if (typeof options === 'function') {
+ cb = options
+ options = {}
+ }
+ const callback = cb || (() => {})
+ this.executor.push({ this: this, fn: this._remove, arguments: [query, options, callback] })
}
/**
* Remove all docs matching the query.
* Use Datastore.removeAsync which has the same signature
* @param {query} query
- * @param {object} [options] Optional options
+ * @param {object} [options={}] Optional options
* @param {boolean} [options.multi = false] If true, can update multiple documents
* @return {Promise} How many documents were removed
* @async
*/
- removeAsync (...args) {
- return this.executor.pushAsync(() => this._removeAsync(...args))
+ removeAsync (query, options = {}) {
+ return this.executor.pushAsync(() => this._removeAsync(query, options))
}
}
diff --git a/lib/persistence.js b/lib/persistence.js
index 414a14e..8588b9e 100755
--- a/lib/persistence.js
+++ b/lib/persistence.js
@@ -164,7 +164,6 @@ class Persistence {
* Do not use directly, it should only used by a {@link Datastore} instance.
* @param {document[]} newDocs Can be empty if no doc was updated/removed
* @return {Promise}
- * @protected
* @see Persistence#persistNewState
*/
async persistNewStateAsync (newDocs) {