diff --git a/API.md b/API.md new file mode 100644 index 0000000..49bdc55 --- /dev/null +++ b/API.md @@ -0,0 +1,1054 @@ +## Classes + +
+
CursorPromise
+

Manage access to data, be it to find, update or remove it.

+

It extends Promise so that its methods (which return this) are chainable & awaitable.

+
DatastoreEventEmitter
+

The Datastore class is the main class of NeDB.

+
Persistence
+

Under the hood, NeDB's persistence uses an append-only format, meaning that all +updates and deletes actually result in lines added at the end of the datafile, +for performance reasons. The database is automatically compacted (i.e. put back +in the one-line-per-document format) every time you load each database within +your application.

+

You can manually call the compaction function +with yourDatabase.persistence.compactDatafile which takes no argument. It +queues a compaction of the datafile in the executor, to be executed sequentially +after all pending operations. The datastore will fire a compaction.done event +once compaction is finished.

+

You can also set automatic compaction at regular intervals +with yourDatabase.persistence.setAutocompactionInterval(interval), interval +in milliseconds (a minimum of 5s is enforced), and stop automatic compaction +with yourDatabase.persistence.stopAutocompaction().

+

Keep in mind that compaction takes a bit of time (not too much: 130ms for 50k +records on a typical development machine) and no other operation can happen when +it does, so most projects actually don't need to use it.

+

Compaction will also immediately remove any documents whose data line has become +corrupted, assuming that the total percentage of all corrupted documents in that +database still falls below the specified corruptAlertThreshold option's value.

+

Durability works similarly to major databases: compaction forces the OS to +physically flush data to disk, while appends to the data file do not (the OS is +responsible for flushing the data). That guarantees that a server crash can +never cause complete data loss, while preserving performance. The worst that can +happen is a crash between two syncs, causing a loss of all data between the two +syncs. Usually syncs are 30 seconds appart so that's at most 30 seconds of +data. This post by Antirez on Redis persistence +explains this in more details, NeDB being very close to Redis AOF persistence +with appendfsync option set to no.

+
+ +## Typedefs + +
+
NoParamCallback : function
+

Callback with no parameter

+
compareStringsnumber
+

String comparison function.

+
  if (a < b) return -1
+  if (a > b) return 1
+  return 0
+
+
MultipleDocumentsCallback : function
+

Callback that returns an Array of documents

+
SingleDocumentCallback : function
+

Callback that returns a single document

+
AsyncFunctionPromise.<*>
+

Generic async function

+
GenericCallback : function
+

Callback with generic parameters

+
document : Object.<string, *>
+

Generic document in NeDB. +It consists of an Object with anything you want inside.

+
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:

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

+
serializationHookstring
+

The beforeDeserialization and afterDeserialization callbacks are hooks which are executed respectively before +parsing each document and after stringifying them. They can be used for example to encrypt the Datastore. +The beforeDeserialization should revert what afterDeserialization has done.

+
rawIndex
+
+
+ + + +## Cursor ⇐ Promise +

Manage access to data, be it to find, update or remove it.

+

It extends Promise so that its methods (which return this) are chainable & awaitable.

+ +**Kind**: global class +**Extends**: Promise + +* [Cursor](#Cursor) ⇐ Promise + * [new Cursor(db, query, [mapFn])](#new_Cursor_new) + * _instance_ + * [.db](#Cursor+db) : [Datastore](#Datastore) + * [.query](#Cursor+query) : [query](#query) + * [.limit(limit)](#Cursor+limit) ⇒ [Cursor](#Cursor) + * [.skip(skip)](#Cursor+skip) ⇒ [Cursor](#Cursor) + * [.sort(sortQuery)](#Cursor+sort) ⇒ [Cursor](#Cursor) + * [.projection(projection)](#Cursor+projection) ⇒ [Cursor](#Cursor) + * [.exec(_callback)](#Cursor+exec) + * [.execAsync()](#Cursor+execAsync) ⇒ Promise.<(Array.<document>\|\*)> + * _inner_ + * [~mapFn](#Cursor..mapFn) ⇒ \* \| Promise.<\*> + * [~execCallback](#Cursor..execCallback) : function + + + +### new Cursor(db, query, [mapFn]) +

Create a new cursor for this collection

+ +**Params** + +- db [Datastore](#Datastore) -

The datastore this cursor is bound to

+- query [query](#query) -

The query this cursor will operate on

+- [mapFn] [mapFn](#Cursor..mapFn) -

Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove

+ + + +### cursor.db : [Datastore](#Datastore) +**Kind**: instance property of [Cursor](#Cursor) +**Access**: protected + + +### cursor.query : [query](#query) +**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** + +- limit Number + + + +### cursor.skip(skip) ⇒ [Cursor](#Cursor) +

Skip a number of results

+ +**Kind**: instance method of [Cursor](#Cursor) +**Params** + +- skip Number + + + +### cursor.sort(sortQuery) ⇒ [Cursor](#Cursor) +

Sort results of the query

+ +**Kind**: instance method of [Cursor](#Cursor) +**Params** + +- sortQuery Object.<string, number> -

sortQuery is { field: order }, field can use the dot-notation, order is 1 for ascending and -1 for descending

+ + + +### cursor.projection(projection) ⇒ [Cursor](#Cursor) +

Add the use of a projection

+ +**Kind**: instance method of [Cursor](#Cursor) +**Params** + +- 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.

+ + + +### 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

+ +**Kind**: instance method of [Cursor](#Cursor) +**Params** + +- _callback [execCallback](#Cursor..execCallback) + + + +### cursor.execAsync() ⇒ Promise.<(Array.<document>\|\*)> +

Async version of [exec](#Cursor+exec).

+ +**Kind**: instance method of [Cursor](#Cursor) +**See**: Cursor#exec + + +### Cursor~mapFn ⇒ \* \| Promise.<\*> +

Has a callback

+ +**Kind**: inner typedef of [Cursor](#Cursor) +**Params** + +- res [Array.<document>](#document) + + + +### Cursor~execCallback : function +**Kind**: inner typedef of [Cursor](#Cursor) +**Params** + +- err Error +- res [Array.<document>](#document) | \* -

If an mapFn was given to the Cursor, then the type of this parameter is the one returned by the mapFn.

+ + + +## Datastore ⇐ [EventEmitter](http://nodejs.org/api/events.html) +

The Datastore class is the main class of NeDB.

+ +**Kind**: global class +**Extends**: [EventEmitter](http://nodejs.org/api/events.html) +**Emits**: Datastore#event:"compaction.done" + +* [Datastore](#Datastore) ⇐ [EventEmitter](http://nodejs.org/api/events.html) + * [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](#new_Executor_new) + * [.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) + * [.ensureIndex(options, callback)](#Datastore+ensureIndex) + * [.ensureIndexAsync(options)](#Datastore+ensureIndexAsync) ⇒ Promise.<void> + * [.removeIndex(fieldName, callback)](#Datastore+removeIndex) + * [.removeIndexAsync(fieldName)](#Datastore+removeIndexAsync) ⇒ Promise.<void> + * [.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 + * [.findOneAsync(query, projection)](#Datastore+findOneAsync) ⇒ [Cursor.<document>](#document) + * [.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> + * ["event:compaction.done"](#Datastore+event_compaction.done) + * _inner_ + * [~countCallback](#Datastore..countCallback) : function + * [~findOneCallback](#Datastore..findOneCallback) : function + * [~updateCallback](#Datastore..updateCallback) : function + * [~removeCallback](#Datastore..removeCallback) : function + + + +### new Datastore(options) +

Create a new collection, either persistent or in-memory.

+

If you use a persistent datastore without the autoload option, you need to call [loadDatabase](#Datastore+loadDatabase) or +[loadDatabaseAsync](#Datastore+loadDatabaseAsync) manually. This function fetches the data from datafile and prepares the database. +Don't forget it! If you use a persistent datastore, no command (insert, find, update, remove) will be executed +before it is called, so make sure to call it yourself or use the autoload option.

+

Also, if loading fails, all commands registered to the [executor](#Datastore+executor) afterwards will not be executed. +They will be registered and executed, in sequence, only after a successful loading.

+ +**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.

+ - [.filename] 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. Not used if options.inMemoryOnly is true.

+ - [.inMemoryOnly] boolean = false -

If set to true, no data will be written in storage. This option has +priority over options.filename.

+ - [.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.

+ - [.onload] [NoParamCallback](#NoParamCallback) -

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.

+ - [.beforeDeserialization] [serializationHook](#serializationHook) -

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

+ - [.afterSerialization] [serializationHook](#serializationHook) -

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.

+ - [.corruptAlertThreshold] 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.

+ + + +### neDB.inMemoryOnly : boolean +

Determines if the Datastore keeps data in-memory, or if it saves it in storage. Is not read after +instanciation.

+ +**Kind**: instance property of [Datastore](#Datastore) +**Access**: protected + + +### neDB.autoload : boolean +

Determines if the Datastore should autoload the database upon instantiation. Is not read after instanciation.

+ +**Kind**: instance property of [Datastore](#Datastore) +**Access**: protected + + +### neDB.timestampData : boolean +

Determines if the Datastore should add createdAt and updatedAt fields automatically if not set by the user.

+ +**Kind**: instance property of [Datastore](#Datastore) +**Access**: protected + + +### neDB.filename : string +

If null, it means inMemoryOnly is true. The filename is the name given to the storage module. Is not read +after instanciation.

+ +**Kind**: instance property of [Datastore](#Datastore) +**Access**: protected + + +### neDB.persistence : [Persistence](#Persistence) +

The Persistence instance for this Datastore.

+ +**Kind**: instance property of [Datastore](#Datastore) + + +### neDB.executor : [Executor](#new_Executor_new) +

The Executor instance for this Datastore. It is used in all methods exposed by the Datastore, any Cursor +produced by the Datastore and by this.persistence.compactDataFile & this.persistence.compactDataFileAsync +to ensure operations are performed sequentially in the database.

+ +**Kind**: instance property of [Datastore](#Datastore) +**Access**: protected + + +### neDB.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 + + +### neDB.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 + + +### neDB.autoloadPromise : Promise +

A Promise that resolves when the autoload has finished.

+

The onload callback is not awaited by this Promise, it is started immediately after that.

+ +**Kind**: instance property of [Datastore](#Datastore) + + +### neDB.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 + + +### neDB.loadDatabase(callback) +

Load the database from the datafile, and trigger the execution of buffered commands if any.

+ +**Kind**: instance method of [Datastore](#Datastore) +**Params** + +- callback [NoParamCallback](#NoParamCallback) + + + +### neDB.loadDatabaseAsync() ⇒ Promise +

Async version of [loadDatabase](#Datastore+loadDatabase).

+ +**Kind**: instance method of [Datastore](#Datastore) +**See**: Datastore#loadDatabase + + +### neDB.getAllData() ⇒ [Array.<document>](#document) +

Get an array of all the data in the database.

+ +**Kind**: instance method of [Datastore](#Datastore) + + +### neDB.ensureIndex(options, callback) +

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.

+ +**Kind**: instance method of [Datastore](#Datastore) +**Params** + +- 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

+ + + +### neDB.ensureIndexAsync(options) ⇒ Promise.<void> +

Async version of [ensureIndex](#Datastore+ensureIndex).

+ +**Kind**: instance method of [Datastore](#Datastore) +**See**: Datastore#ensureIndex +**Params** + +- 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

+ + + +### neDB.removeIndex(fieldName, callback) +

Remove an index +Previous versions said explicitly the callback was optional, it is now recommended setting one.

+ +**Kind**: instance method of [Datastore](#Datastore) +**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.

+- callback [NoParamCallback](#NoParamCallback) -

Optional callback, signature: err

+ + + +### neDB.removeIndexAsync(fieldName) ⇒ Promise.<void> +

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.

+ + + +### neDB.insertAsync(newDoc) ⇒ [Promise.<document>](#document) +

Async version of [Datastore#insert](Datastore#insert).

+ +**Kind**: instance method of [Datastore](#Datastore) +**Params** + +- newDoc [document](#document) | [Array.<document>](#document) + + + +### neDB.count(query, [callback]) ⇒ Cursor.<number> \| undefined +

Count all documents matching the query.

+ +**Kind**: instance method of [Datastore](#Datastore) +**Params** + +- query [query](#query) -

MongoDB-style query

+- [callback] [countCallback](#Datastore..countCallback) -

If given, the function will return undefined, otherwise it will return the Cursor.

+ + + +### neDB.countAsync(query) ⇒ Cursor.<number> +

Async version of [count](#Datastore+count).

+ +**Kind**: instance method of [Datastore](#Datastore) +**Returns**: Cursor.<number> -

count

+**Params** + +- query [query](#query) -

MongoDB-style query

+ + + +### neDB.find(query, [projection], [callback]) ⇒ Cursor.<Array.<document>> \| undefined +

Find all documents matching the query +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** + +- 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

+ + + +### neDB.findAsync(query, [projection]) ⇒ Cursor.<Array.<document>> +

Async version of [find](#Datastore+find).

+ +**Kind**: instance method of [Datastore](#Datastore) +**Params** + +- query [query](#query) -

MongoDB-style query

+- [projection] [projection](#projection) = {} -

MongoDB-style projection

+ + + +### neDB.findOne(query, [projection], [callback]) ⇒ [Cursor.<document>](#document) \| undefined +

Find one document matching the query.

+ +**Kind**: instance method of [Datastore](#Datastore) +**Params** + +- query [query](#query) -

MongoDB-style query

+- [projection] [projection](#projection) | [SingleDocumentCallback](#SingleDocumentCallback) = {} -

MongoDB-style projection

+- [callback] [SingleDocumentCallback](#SingleDocumentCallback) -

Optional callback, signature: err, doc

+ + + +### neDB.findOneAsync(query, projection) ⇒ [Cursor.<document>](#document) +

Async version of [findOne](#Datastore+findOne).

+ +**Kind**: instance method of [Datastore](#Datastore) +**See**: Datastore#findOne +**Params** + +- query [query](#query) -

MongoDB-style query

+- projection [projection](#projection) -

MongoDB-style projection

+ + + +### neDB.update(query, update, [options|], [cb]) +

Update all docs matching query.

+ +**Kind**: instance method of [Datastore](#Datastore) +**Params** + +- 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!). Using a new document will replace the +matched docs. Using a set of modifiers will 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

+ + + +### neDB.updateAsync(query, update, [options]) ⇒ Promise.<{numAffected: number, affectedDocuments: (Array.<document>\|document\|null), upsert: boolean}> +

Async version of [update](#Datastore+update).

+ +**Kind**: instance method of [Datastore](#Datastore) +**See**: Datastore#update +**Params** + +- 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!). Using a new document will replace the +matched docs. Using a set of modifiers will 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.

+ + + +### neDB.remove(query, [options], [cb]) +

Remove all docs matching the query.

+ +**Kind**: instance method of [Datastore](#Datastore) +**Params** + +- 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

+ + + +### neDB.removeAsync(query, [options]) ⇒ Promise.<number> +

Remove all docs matching the query. +Use Datastore.removeAsync which has the same signature

+ +**Kind**: instance method of [Datastore](#Datastore) +**Returns**: Promise.<number> -

How many documents were removed

+**Params** + +- 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. +It happens when calling datastore.persistence.compactDatafile, which is called periodically if you have called +datastore.persistence.setAutocompactionInterval.

+ +**Kind**: event emitted by [Datastore](#Datastore) + + +### Datastore~countCallback : function +**Kind**: inner typedef of [Datastore](#Datastore) +**Params** + +- err Error +- count number + + + +### Datastore~findOneCallback : function +**Kind**: inner typedef of [Datastore](#Datastore) +**Params** + +- err Error +- doc [document](#document) + + + +### Datastore~updateCallback : function +

If update was an upsert, upsert flag is set to true, affectedDocuments can be one of the following:

+ +

WARNING: The API was changed between v1.7.4 and v1.8, for consistency and readability reasons. Prior and +including to v1.7.4, the callback signature was (err, numAffected, updated) where updated was the updated document +in case of an upsert or the array of updated documents for an update if the returnUpdatedDocs option was true. That +meant that the type of affectedDocuments in a non multi update depended on whether there was an upsert or not, +leaving only two ways for the user to check whether an upsert had occured: checking the type of affectedDocuments +or running another find query on the whole dataset to check its size. Both options being ugly, the breaking change +was necessary.

+ +**Kind**: inner typedef of [Datastore](#Datastore) +**Params** + +- err Error +- numAffected number +- affectedDocuments [?Array.<document>](#document) | [document](#document) +- upsert boolean + + + +### Datastore~removeCallback : function +**Kind**: inner typedef of [Datastore](#Datastore) +**Params** + +- err Error +- numRemoved number + + + +## Persistence +

Under the hood, NeDB's persistence uses an append-only format, meaning that all +updates and deletes actually result in lines added at the end of the datafile, +for performance reasons. The database is automatically compacted (i.e. put back +in the one-line-per-document format) every time you load each database within +your application.

+

You can manually call the compaction function +with yourDatabase.persistence.compactDatafile which takes no argument. It +queues a compaction of the datafile in the executor, to be executed sequentially +after all pending operations. The datastore will fire a compaction.done event +once compaction is finished.

+

You can also set automatic compaction at regular intervals +with yourDatabase.persistence.setAutocompactionInterval(interval), interval +in milliseconds (a minimum of 5s is enforced), and stop automatic compaction +with yourDatabase.persistence.stopAutocompaction().

+

Keep in mind that compaction takes a bit of time (not too much: 130ms for 50k +records on a typical development machine) and no other operation can happen when +it does, so most projects actually don't need to use it.

+

Compaction will also immediately remove any documents whose data line has become +corrupted, assuming that the total percentage of all corrupted documents in that +database still falls below the specified corruptAlertThreshold option's value.

+

Durability works similarly to major databases: compaction forces the OS to +physically flush data to disk, while appends to the data file do not (the OS is +responsible for flushing the data). That guarantees that a server crash can +never cause complete data loss, while preserving performance. The worst that can +happen is a crash between two syncs, causing a loss of all data between the two +syncs. Usually syncs are 30 seconds appart so that's at most 30 seconds of +data. This post by Antirez on Redis persistence +explains this in more details, NeDB being very close to Redis AOF persistence +with appendfsync option set to no.

+ +**Kind**: global class + +* [Persistence](#Persistence) + * [new Persistence()](#new_Persistence_new) + * _instance_ + * [.persistCachedDatabaseAsync()](#Persistence+persistCachedDatabaseAsync) ⇒ Promise.<void> + * [.compactDatafile([callback])](#Persistence+compactDatafile) + * [.compactDatafileAsync()](#Persistence+compactDatafileAsync) + * [.setAutocompactionInterval(interval)](#Persistence+setAutocompactionInterval) + * [.stopAutocompaction()](#Persistence+stopAutocompaction) + * [.persistNewStateAsync(newDocs)](#Persistence+persistNewStateAsync) ⇒ Promise + * [.treatRawData(rawData)](#Persistence+treatRawData) ⇒ Object + * [.treatRawStreamAsync(rawStream)](#Persistence+treatRawStreamAsync) ⇒ Promise.<{data: Array.<document>, indexes: Object.<string, rawIndex>}> + * [.loadDatabase(callback)](#Persistence+loadDatabase) + * [.loadDatabaseAsync()](#Persistence+loadDatabaseAsync) ⇒ Promise.<void> + * _static_ + * [.ensureDirectoryExistsAsync(dir)](#Persistence.ensureDirectoryExistsAsync) ⇒ Promise.<void> + + + +### new Persistence() +

Create a new Persistence object for database options.db

+ +**Params** + + - .db [Datastore](#Datastore) + - [.corruptAlertThreshold] Number -

Optional, threshold after which an alert is thrown if too much data is corrupt

+ - [.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.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](#Persistence+compactDatafileAsync) which uses the [executor](#Datastore+executor).

+ +**Kind**: instance method of [Persistence](#Persistence) +**Access**: protected + + +### persistence.compactDatafile([callback]) +

Queue a rewrite of the datafile

+ +**Kind**: instance method of [Persistence](#Persistence) +**See**: Persistence#persistCachedDatabaseAsync +**Params** + +- [callback] [NoParamCallback](#NoParamCallback) = () => {} + + + +### persistence.compactDatafileAsync() +

Async version of [compactDatafile](#Persistence+compactDatafile).

+ +**Kind**: instance method of [Persistence](#Persistence) +**See**: Persistence#compactDatafile + + +### persistence.setAutocompactionInterval(interval) +

Set automatic compaction every interval ms

+ +**Kind**: instance method of [Persistence](#Persistence) +**Params** + +- interval Number -

in milliseconds, with an enforced minimum of 5000 milliseconds

+ + + +### persistence.stopAutocompaction() +

Stop autocompaction (do nothing if automatic compaction was not running)

+ +**Kind**: instance method of [Persistence](#Persistence) + + +### persistence.persistNewStateAsync(newDocs) ⇒ Promise +

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) +**Params** + +- 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.

+

Do not use directly, it should only used by a [Datastore](#Datastore) instance.

+ +**Kind**: instance method of [Persistence](#Persistence) +**Access**: protected +**Params** + +- rawData string -

database file

+ + + +### persistence.treatRawStreamAsync(rawStream) ⇒ Promise.<{data: Array.<document>, indexes: Object.<string, rawIndex>}> +

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** + +- rawStream Readable + + + +### persistence.loadDatabase(callback) +

Load the database

+
    +
  1. Create all indexes
  2. +
  3. Insert all data
  4. +
  5. Compact the database
  6. +
+

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** + +- callback [NoParamCallback](#NoParamCallback) + + + +### persistence.loadDatabaseAsync() ⇒ Promise.<void> +

Async version of [loadDatabase](#Persistence+loadDatabase)

+ +**Kind**: instance method of [Persistence](#Persistence) +**See**: Persistence#loadDatabase + + +### Persistence.ensureDirectoryExistsAsync(dir) ⇒ Promise.<void> +

Check if a directory stat and create it on the fly if it is not the case.

+ +**Kind**: static method of [Persistence](#Persistence) +**Params** + +- dir string + + + +## 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 \* + + + +## GenericCallback : function +

Callback with generic parameters

+ +**Kind**: global typedef +**Params** + +- err Error +- ...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:

+ + +**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 are hooks which are executed respectively before +parsing each document and after stringifying them. They can be used for example to encrypt the Datastore. +The beforeDeserialization should revert what afterDeserialization has done.

+ +**Kind**: global typedef +**Params** + +- x string + + + +## rawIndex +**Kind**: global typedef +**Properties** + +| Name | Type | +| --- | --- | +| fieldName | string | +| [unique] | boolean | +| [sparse] | boolean | + diff --git a/README.md b/README.md index dbd6331..0465e8a 100755 --- a/README.md +++ b/README.md @@ -55,11 +55,11 @@ documentation is available in the [`docs`](./docs) directory of the repository. You can use NeDB as an in-memory only datastore or as a persistent datastore. One datastore is the equivalent of a MongoDB collection. The constructor is used -as follows [`new Datastore(options)` where `options` is an object](./docs/Datastore.md#new_Datastore_new). +as follows [`new Datastore(options)` where `options` is an object](./API.md#new_Datastore_new). -If the Datastore is persistent (if you give it [`options.filename`](./docs/Datastore.md#Datastore+filename), -you'll need to load the database using [Datastore#loadDatabaseAsync](./docs/Datastore.md#Datastore+loadDatabaseAsync), -or using [`options.autoload`](./docs/Datastore.md#Datastore+autoload). +If the Datastore is persistent (if you give it [`options.filename`](./API.md#Datastore+filename), +you'll need to load the database using [Datastore#loadDatabaseAsync](./API.md#Datastore+loadDatabaseAsync), +or using [`options.autoload`](./API.md#Datastore+autoload). ```javascript // Type 1: In-memory only datastore (no need to load the database) @@ -101,11 +101,11 @@ compacted (i.e. put back in the one-line-per-document format) every time you load each database within your application. You can manually call the compaction function -with [`yourDatabase#persistence#compactDatafileAsync`](./docs/Persistence.md#Persistence+compactDatafileAsync). +with [`yourDatabase#persistence#compactDatafileAsync`](./API.md#Persistence+compactDatafileAsync). You can also set automatic compaction at regular intervals -with [`yourDatabase#persistence#setAutocompactionInterval`](./docs/Persistence.md#Persistence+setAutocompactionInterval), -and stop automatic compaction with [`yourDatabase#persistence#stopAutocompaction`](./docs/Persistence.md#Persistence+stopAutocompaction). +with [`yourDatabase#persistence#setAutocompactionInterval`](./API.md#Persistence+setAutocompactionInterval), +and stop automatic compaction with [`yourDatabase#persistence#stopAutocompaction`](./API.md#Persistence+stopAutocompaction). ### Inserting documents @@ -387,17 +387,17 @@ const docs = await db.findAsync({ #### Sorting and paginating -[`Datastore#findAsync`](./docs/Datastore.md#Datastore+findAsync), -[`Datastore#findOneAsync`](./docs/Datastore.md#Datastore+findOneAsync) and -[`Datastore#countAsync`](./docs/Datastore.md#Datastore+countAsync) don't +[`Datastore#findAsync`](./API.md#Datastore+findAsync), +[`Datastore#findOneAsync`](./API.md#Datastore+findOneAsync) and +[`Datastore#countAsync`](./API.md#Datastore+countAsync) don't actually return a `Promise`, but a [`Cursor`](./docs/Cursor.md) which is a [`Thenable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#thenable_objects) -which calls [`Cursor#execAsync`](./docs/Cursor.md#Cursor+execAsync) when awaited. +which calls [`Cursor#execAsync`](./API.md#Cursor+execAsync) when awaited. -This pattern allows to chain [`Cursor#sort`](./docs/Cursor.md#Cursor+sort), -[`Cursor#skip`](./docs/Cursor.md#Cursor+skip), -[`Cursor#limit`](./docs/Cursor.md#Cursor+limit) and -[`Cursor#projection`](./docs/Cursor.md#Cursor+projection) and await the result. +This pattern allows to chain [`Cursor#sort`](./API.md#Cursor+sort), +[`Cursor#skip`](./API.md#Cursor+skip), +[`Cursor#limit`](./API.md#Cursor+limit) and +[`Cursor#projection`](./API.md#Cursor+projection) and await the result. ```javascript // Let's say the database contains these 4 documents @@ -486,14 +486,14 @@ const count = await db.countAsync({}) ### Updating documents -[`db.updateAsync(query, update, options)`](./docs/Datastore.md#Datastore+updateAsync) +[`db.updateAsync(query, update, options)`](./API.md#Datastore+updateAsync) will update all documents matching `query` according to the `update` rules. `update` specifies how the documents should be modified. It is either a new document or a set of modifiers (you cannot use both together): * A new document will replace the matched docs; * Modifiers create the fields they need to modify if they don't exist, - and you can apply them to subdocs (see [the API reference]((./docs/Datastore.md#Datastore+updateAsync))) + and you can apply them to subdocs (see [the API reference]((./API.md#Datastore+updateAsync))) `options` is an object with three possible parameters: * `multi` which allows the modification of several documents if set to true. @@ -637,7 +637,7 @@ await db.updateAsync({ _id: 'id1' }, { $min: { value: 8 } }, {}) ### Removing documents -[`db.removeAsync(query, options)`](./docs/Datastore.md#Datastore#removeAsync) +[`db.removeAsync(query, options)`](./API.md#Datastore#removeAsync) will remove documents matching `query`. Can remove multiple documents if `options.multi` is set. Returns the `Promise`. @@ -672,7 +672,7 @@ fields in nested documents using the dot notation. For now, indexes are only used to speed up basic queries and queries using `$in`, `$lt`, `$lte`, `$gt` and `$gte`. The indexed values cannot be of type array of object. -To create an index, use [`datastore#ensureIndexAsync(options)`](./docs/Datastore.md#Datastore+ensureIndexAsync). +To create an index, use [`datastore#ensureIndexAsync(options)`](./API.md#Datastore+ensureIndexAsync). It resolves when the index is persisted on disk (if the database is persistent) and may throw an Error (usually a unique constraint that was violated). It can be called when you want, even after some data was inserted, though it's best to @@ -690,7 +690,7 @@ call it at application startup. The options are: Note: the `_id` is automatically indexed with a unique constraint. You can remove a previously created index with -[`datastore#removeIndexAsync(fieldName)`](./docs/Datastore.md#Datastore+removeIndexAsync). +[`datastore#removeIndexAsync(fieldName)`](./API.md#Datastore+removeIndexAsync). ```javascript try { diff --git a/browser-version/lib/customUtils.js b/browser-version/lib/customUtils.js index eb40b27..cc05357 100755 --- a/browser-version/lib/customUtils.js +++ b/browser-version/lib/customUtils.js @@ -2,6 +2,7 @@ * Utility functions that need to be reimplemented for each environment. * This is the version for the browser & React-Native * @module customUtilsBrowser + * @private */ /** diff --git a/browser-version/lib/storage.browser.js b/browser-version/lib/storage.browser.js index a69c0b4..1548a07 100755 --- a/browser-version/lib/storage.browser.js +++ b/browser-version/lib/storage.browser.js @@ -117,7 +117,7 @@ const readFileAsync = async (filename, options) => { * @param {string} filename * @return {Promise} * @async - * @alias module:storageBrowser + * @alias module:storageBrowser.unlink */ const unlinkAsync = async filename => { try { diff --git a/docs/Cursor.md b/docs/Cursor.md deleted file mode 100644 index cf07df1..0000000 --- a/docs/Cursor.md +++ /dev/null @@ -1,181 +0,0 @@ - - -## Cursor ⇐ Promise -

Manage access to data, be it to find, update or remove it.

-

It extends Promise so that its methods (which return this) are chainable & awaitable.

- -**Kind**: global class -**Extends**: Promise - -* [Cursor](#Cursor) ⇐ Promise - * [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) - * [.projection(projection)](#Cursor+projection) ⇒ [Cursor](#Cursor) - * [.project(candidates)](#Cursor+project) ⇒ [Array.<document>](#document) - * [._execAsync()](#Cursor+_execAsync) ⇒ [Array.<document>](#document) \| Promise.<\*> - * [._exec(_callback)](#Cursor+_exec) - * [.exec(_callback)](#Cursor+exec) - * [.execAsync()](#Cursor+execAsync) ⇒ Promise.<(Array.<document>\|\*)> - * _inner_ - * [~execFnWithCallback](#Cursor..execFnWithCallback) : function - * [~execFnWithoutCallback](#Cursor..execFnWithoutCallback) ⇒ Promise \| \* - * [~execCallback](#Cursor..execCallback) : function - - - -### new Cursor(db, query, [execFn], [hasCallback]) -

Create a new cursor for this collection

- -**Params** - -- db [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).

- - - -### cursor.db : [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** - -- limit Number - - - -### cursor.skip(skip) ⇒ [Cursor](#Cursor) -

Skip a number of results

- -**Kind**: instance method of [Cursor](#Cursor) -**Params** - -- skip Number - - - -### cursor.sort(sortQuery) ⇒ [Cursor](#Cursor) -

Sort results of the query

- -**Kind**: instance method of [Cursor](#Cursor) -**Params** - -- sortQuery Object.<string, number> -

sortQuery is { field: order }, field can use the dot-notation, order is 1 for ascending and -1 for descending

- - - -### cursor.projection(projection) ⇒ [Cursor](#Cursor) -

Add the use of a projection

- -**Kind**: instance method of [Cursor](#Cursor) -**Params** - -- 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.

- - - -### cursor.project(candidates) ⇒ [Array.<document>](#document) -

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** - -- candidates [Array.<document>](#document) - - - -### cursor.\_execAsync() ⇒ [Array.<document>](#document) \| Promise.<\*> -

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 execAsync which uses the executor

- -**Kind**: instance method of [Cursor](#Cursor) - - -### 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](#Cursor+exec) which uses the [executor](#Datastore+executor).

- -**Kind**: instance method of [Cursor](#Cursor) -**Access**: protected -**See**: Cursor#exec -**Params** - -- _callback [execCallback](#Cursor..execCallback) - - - -### 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

- -**Kind**: instance method of [Cursor](#Cursor) -**Params** - -- _callback [execCallback](#Cursor..execCallback) - - - -### cursor.execAsync() ⇒ Promise.<(Array.<document>\|\*)> -

Async version of [exec](#Cursor+exec).

- -**Kind**: instance method of [Cursor](#Cursor) -**See**: Cursor#exec - - -### Cursor~execFnWithCallback : function -

Has a callback

- -**Kind**: inner typedef of [Cursor](#Cursor) -**Params** - -- err Error -- res [?Array.<document>](#document) | [document](#document) - - - -### Cursor~execFnWithoutCallback ⇒ Promise \| \* -

Does not have a callback, may return a Promise.

- -**Kind**: inner typedef of [Cursor](#Cursor) -**Params** - -- res [?Array.<document>](#document) | [document](#document) - - - -### Cursor~execCallback : function -**Kind**: inner typedef of [Cursor](#Cursor) -**Params** - -- 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.

- diff --git a/docs/Datastore.md b/docs/Datastore.md deleted file mode 100644 index bd2a3f7..0000000 --- a/docs/Datastore.md +++ /dev/null @@ -1,568 +0,0 @@ - - -## Datastore ⇐ EventEmitter -

The Datastore class is the main class of NeDB.

- -**Kind**: global class -**Extends**: EventEmitter -**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(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 - * [.findOneAsync(query, projection)](#Datastore+findOneAsync) ⇒ [Cursor.<document>](#document) - * [.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> - * ["event:compaction.done"](#Datastore+event_compaction.done) - * _inner_ - * [~countCallback](#Datastore..countCallback) : function - * [~findOneCallback](#Datastore..findOneCallback) : function - * [~updateCallback](#Datastore..updateCallback) : function - * [~removeCallback](#Datastore..removeCallback) : function - - - -### new Datastore(options) -

Create a new collection, either persistent or in-memory.

-

If you use a persistent datastore without the autoload option, you need to call loadDatabase manually. This -function fetches the data from datafile and prepares the database. Don't forget it! If you use a persistent -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.

- - [.filename] 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.

- - [.inMemoryOnly] 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.

- - [.onload] 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.

- - [.beforeDeserialization] 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).

- - [.afterSerialization] 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.

- - [.corruptAlertThreshold] 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.

- - [.nodeWebkitAppName] 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.inMemoryOnly : boolean -

Determines if the Datastore keeps data in-memory, or if it saves it in storage. Is not read after -instanciation.

- -**Kind**: instance property of [Datastore](#Datastore) -**Access**: protected - - -### datastore.autoload : boolean -

Determines if the Datastore should autoload the database upon instantiation. Is not read after instanciation.

- -**Kind**: instance property of [Datastore](#Datastore) -**Access**: protected - - -### datastore.timestampData : boolean -

Determines if the Datastore should add createdAt and updatedAt fields automatically if not set by the user.

- -**Kind**: instance property of [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.

- -**Kind**: instance property of [Datastore](#Datastore) -**Access**: protected - - -### datastore.persistence : [Persistence](#Persistence) -

The Persistence instance for this Datastore.

- -**Kind**: instance property of [Datastore](#Datastore) - - -### datastore.executor : [Executor](#Executor) -

The Executor instance for this Datastore. It is used in all methods exposed by the Datastore, any Cursor -produced by the Datastore and by this.persistence.compactDataFile & this.persistence.compactDataFileAsync -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 -

A Promise that resolves when the autoload has finished.

-

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** - -- callback function - - - -### datastore.loadDatabaseAsync() ⇒ Promise -

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.

- -**Kind**: instance method of [Datastore](#Datastore) - - -### 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) -

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.

- -**Kind**: instance method of [Datastore](#Datastore) -**Params** - -- 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> -

Async version of [ensureIndex](#Datastore+ensureIndex).

- -**Kind**: instance method of [Datastore](#Datastore) -**See**: Datastore#ensureIndex -**Params** - -- 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

- - - -### datastore.removeIndex(fieldName, callback) -

Remove an index -Previous versions said explicitly the callback was optional, it is now recommended setting one.

- -**Kind**: instance method of [Datastore](#Datastore) -**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.

-- callback [NoParamCallback](#NoParamCallback) -

Optional callback, signature: err

- - - -### datastore.removeIndexAsync(fieldName) ⇒ Promise.<void> -

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** - -- doc [document](#document) - - - -### datastore.removeFromIndexes(doc) -

Remove one or several document(s) from all indexes.

-

This is an internal function.

- -**Kind**: instance method of [Datastore](#Datastore) -**Access**: protected -**Params** - -- 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.

-

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** - -- 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) -

Async version of [Datastore#insert](Datastore#insert).

- -**Kind**: instance method of [Datastore](#Datastore) -**Params** - -- newDoc [document](#document) | [Array.<document>](#document) - - - -### datastore.count(query, [callback]) ⇒ Cursor.<number> \| undefined -

Count all documents matching the query.

- -**Kind**: instance method of [Datastore](#Datastore) -**Params** - -- 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> -

Async version of [count](#Datastore+count).

- -**Kind**: instance method of [Datastore](#Datastore) -**Returns**: Cursor.<number> -

count

-**Params** - -- query [query](#query) -

MongoDB-style query

- - - -### datastore.find(query, [projection], [callback]) ⇒ Cursor.<Array.<document>> \| undefined -

Find all documents matching the query -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** - -- 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>> -

Async version of [find](#Datastore+find).

- -**Kind**: instance method of [Datastore](#Datastore) -**Params** - -- 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.

- -**Kind**: instance method of [Datastore](#Datastore) -**Params** - -- 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) -

Async version of [findOne](#Datastore+findOne).

- -**Kind**: instance method of [Datastore](#Datastore) -**See**: Datastore#findOne -**Params** - -- query [query](#query) -

MongoDB-style query

-- projection [projection](#projection) -

MongoDB-style projection

- - - -### datastore.update(query, update, [options|], [cb]) -

Update all docs matching query.

- -**Kind**: instance method of [Datastore](#Datastore) -**Params** - -- 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!). Using a new document will replace the -matched docs. Using a set of modifiers will 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}> -

Async version of [update](#Datastore+update).

- -**Kind**: instance method of [Datastore](#Datastore) -**See**: Datastore#update -**Params** - -- 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!). Using a new document will replace the -matched docs. Using a set of modifiers will 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.

- - - -### datastore.remove(query, [options], [cb]) -

Remove all docs matching the query.

- -**Kind**: instance method of [Datastore](#Datastore) -**Params** - -- 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

- - - -### datastore.removeAsync(query, [options]) ⇒ Promise.<number> -

Remove all docs matching the query. -Use Datastore.removeAsync which has the same signature

- -**Kind**: instance method of [Datastore](#Datastore) -**Returns**: Promise.<number> -

How many documents were removed

-**Params** - -- 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. -It happens when calling datastore.persistence.compactDatafile, which is called periodically if you have called -datastore.persistence.setAutocompactionInterval.

- -**Kind**: event emitted by [Datastore](#Datastore) - - -### Datastore~countCallback : function -**Kind**: inner typedef of [Datastore](#Datastore) -**Params** - -- err Error -- count number - - - -### Datastore~findOneCallback : function -**Kind**: inner typedef of [Datastore](#Datastore) -**Params** - -- err Error -- doc [document](#document) - - - -### Datastore~updateCallback : function -

If update was an upsert, upsert flag is set to true, affectedDocuments can be one of the following:

- -

WARNING: The API was changed between v1.7.4 and v1.8, for consistency and readability reasons. Prior and -including to v1.7.4, the callback signature was (err, numAffected, updated) where updated was the updated document -in case of an upsert or the array of updated documents for an update if the returnUpdatedDocs option was true. That -meant that the type of affectedDocuments in a non multi update depended on whether there was an upsert or not, -leaving only two ways for the user to check whether an upsert had occured: checking the type of affectedDocuments -or running another find query on the whole dataset to check its size. Both options being ugly, the breaking change -was necessary.

- -**Kind**: inner typedef of [Datastore](#Datastore) -**Params** - -- err Error -- numAffected number -- affectedDocuments [?Array.<document>](#document) | [document](#document) -- upsert boolean - - - -### Datastore~removeCallback : function -**Kind**: inner typedef of [Datastore](#Datastore) -**Params** - -- err Error -- numRemoved number - diff --git a/docs/Executor.md b/docs/Executor.md deleted file mode 100644 index 1d24696..0000000 --- a/docs/Executor.md +++ /dev/null @@ -1,57 +0,0 @@ - - -## Executor -

Executes operations sequentially. -Has an option for a buffer that can be triggered afterwards.

- -**Kind**: global class - -* [Executor](#Executor) - * [new Executor()](#new_Executor_new) - * [.push(task, [forceQueuing])](#Executor+push) - * [.pushAsync(task, [forceQueuing])](#Executor+pushAsync) ⇒ Promise.<\*> - * [.processBuffer()](#Executor+processBuffer) - - - -### new Executor() -

Instantiates a new Executor.

- - - -### executor.push(task, [forceQueuing]) -

If executor is ready, queue task (and process it immediately if executor was idle) -If not, buffer task for later processing

- -**Kind**: instance method of [Executor](#Executor) -**Params** - -- 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.<\*> -

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** - -- task [AsyncFunction](#AsyncFunction) -- [forceQueuing] boolean = false - - - -### executor.processBuffer() -

Queue all tasks in buffer (in the same order they came in) -Automatically sets executor as ready

- -**Kind**: instance method of [Executor](#Executor) diff --git a/docs/Index.md b/docs/Index.md deleted file mode 100644 index fd1716d..0000000 --- a/docs/Index.md +++ /dev/null @@ -1,161 +0,0 @@ - - -## Index -

Indexes on field names, with atomic operations and which can optionally enforce a unique constraint or allow indexed -fields to be undefined

- -**Kind**: global class - -* [Index](#Index) - * [new Index(options)](#new_Index_new) - * [.fieldName](#Index+fieldName) : string - * [.unique](#Index+unique) : boolean - * [.sparse](#Index+sparse) : boolean - * [.treeOptions](#Index+treeOptions) : Object - * [.tree](#Index+tree) : AVLTree - * [.reset([newData])](#Index+reset) - * [.insert(doc)](#Index+insert) - * [.remove(doc)](#Index+remove) - * [.update(oldDoc, [newDoc])](#Index+update) - * [.revertUpdate(oldDoc, [newDoc])](#Index+revertUpdate) - * [.getMatching(value)](#Index+getMatching) ⇒ [Array.<document>](#document) - * [.getBetweenBounds(query)](#Index+getBetweenBounds) ⇒ [Array.<document>](#document) - * [.getAll()](#Index+getAll) ⇒ [Array.<document>](#document) - - - -### new Index(options) -

Create a new index -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** - -- 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)

- - - -### index.fieldName : string -

On which field the index applies to (may use dot notation to index on sub fields).

- -**Kind**: instance property of [Index](#Index) - - -### index.unique : boolean -

Defines if the index enforces a unique constraint for this index.

- -**Kind**: instance property of [Index](#Index) - - -### index.sparse : boolean -

Defines if we can have documents for which fieldName is undefined

- -**Kind**: instance property of [Index](#Index) - - -### index.treeOptions : Object -

Options object given to the underlying BinarySearchTree.

- -**Kind**: instance property of [Index](#Index) - - -### index.tree : AVLTree -

Underlying BinarySearchTree for this index. Uses an AVLTree for optimization.

- -**Kind**: instance property of [Index](#Index) - - -### index.reset([newData]) -

Reset an index

- -**Kind**: instance method of [Index](#Index) -**Params** - -- [newData] [document](#document) | [?Array.<document>](#document) -

Data to initialize the index with. If an error is thrown during -insertion, the index is not modified.

- - - -### index.insert(doc) -

Insert a new document in the index -If an array is passed, we insert all its elements (if one insertion fails the index is not modified) -O(log(n))

- -**Kind**: instance method of [Index](#Index) -**Params** - -- doc [document](#document) | [Array.<document>](#document) -

The document, or array of documents, to insert.

- - - -### index.remove(doc) -

Removes a document from the index. -If an array is passed, we remove all its elements -The remove operation is safe with regards to the 'unique' constraint -O(log(n))

- -**Kind**: instance method of [Index](#Index) -**Params** - -- doc [Array.<document>](#document) | [document](#document) -

The document, or Array of documents, to remove.

- - - -### index.update(oldDoc, [newDoc]) -

Update a document in the index -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** - -- 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.

- - - -### index.revertUpdate(oldDoc, [newDoc]) -

Revert an update

- -**Kind**: instance method of [Index](#Index) -**Params** - -- 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.

- - - -### index.getMatching(value) ⇒ [Array.<document>](#document) -

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** - -- value Array.<\*> | \* -

Value to match the key against

- - - -### index.getBetweenBounds(query) ⇒ [Array.<document>](#document) -

Get all documents in index whose key is between bounds are they are defined by query -Documents are sorted by key

- -**Kind**: instance method of [Index](#Index) -**Params** - -- 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.

- - - -### index.getAll() ⇒ [Array.<document>](#document) -

Get all elements in the index

- -**Kind**: instance method of [Index](#Index) diff --git a/docs/Persistence.md b/docs/Persistence.md deleted file mode 100644 index 1b4c51c..0000000 --- a/docs/Persistence.md +++ /dev/null @@ -1,242 +0,0 @@ - - -## Persistence -

Handle every persistence-related task

- -**Kind**: global class - -* [Persistence](#Persistence) - * [new Persistence()](#new_Persistence_new) - * _instance_ - * [.persistCachedDatabase([callback])](#Persistence+persistCachedDatabase) - * [.persistCachedDatabaseAsync()](#Persistence+persistCachedDatabaseAsync) ⇒ Promise.<void> - * [.compactDatafile([callback])](#Persistence+compactDatafile) - * [.compactDatafileAsync()](#Persistence+compactDatafileAsync) - * [.setAutocompactionInterval(interval)](#Persistence+setAutocompactionInterval) - * [.stopAutocompaction()](#Persistence+stopAutocompaction) - * [.persistNewState(newDocs, [callback])](#Persistence+persistNewState) - * [.persistNewStateAsync(newDocs)](#Persistence+persistNewStateAsync) ⇒ Promise - * [.treatRawData(rawData)](#Persistence+treatRawData) ⇒ Object - * [.treatRawStream(rawStream, cb)](#Persistence+treatRawStream) - * [.treatRawStreamAsync(rawStream)](#Persistence+treatRawStreamAsync) ⇒ Promise.<{data: Array.<document>, indexes: Object.<string, rawIndex>}> - * [.loadDatabase(callback)](#Persistence+loadDatabase) - * [.loadDatabaseAsync()](#Persistence+loadDatabaseAsync) ⇒ Promise.<void> - * _static_ - * [.ensureDirectoryExists(dir, [callback])](#Persistence.ensureDirectoryExists) - * [.ensureDirectoryExistsAsync(dir)](#Persistence.ensureDirectoryExistsAsync) ⇒ Promise.<void> - * ~~[.getNWAppFilename(appName, relativeFilename)](#Persistence.getNWAppFilename) ⇒ string~~ - * _inner_ - * [~treatRawStreamCallback](#Persistence..treatRawStreamCallback) : function - - - -### new Persistence() -

Create a new Persistence object for database options.db

- -**Params** - - - .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]) -

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](#Persistence+compactDatafile) which uses the [executor](#Datastore+executor).

- -**Kind**: instance method of [Persistence](#Persistence) -**Access**: protected -**Params** - -- [callback] [NoParamCallback](#NoParamCallback) = () => {} - - - -### persistence.persistCachedDatabaseAsync() ⇒ Promise.<void> -

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** - -- [callback] [NoParamCallback](#NoParamCallback) = () => {} - - - -### persistence.compactDatafileAsync() -

Async version of [compactDatafile](#Persistence+compactDatafile).

- -**Kind**: instance method of [Persistence](#Persistence) -**See**: Persistence#compactDatafile - - -### persistence.setAutocompactionInterval(interval) -

Set automatic compaction every interval ms

- -**Kind**: instance method of [Persistence](#Persistence) -**Params** - -- interval Number -

in milliseconds, with an enforced minimum of 5000 milliseconds

- - - -### persistence.stopAutocompaction() -

Stop autocompaction (do nothing if automatic compaction was not running)

- -**Kind**: instance method of [Persistence](#Persistence) - - -### 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** - -- newDocs Array.<string> -

Can be empty if no doc was updated/removed

-- [callback] [NoParamCallback](#NoParamCallback) = () => {} - - - -### persistence.persistNewStateAsync(newDocs) ⇒ Promise -

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

-

Do not use directly, it should only used by a [Datastore](#Datastore) instance.

- -**Kind**: instance method of [Persistence](#Persistence) -**Access**: protected -**Params** - -- rawData string -

database file

- - - -### persistence.treatRawStream(rawStream, cb) -

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** - -- rawStream Readable -- cb [treatRawStreamCallback](#Persistence..treatRawStreamCallback) - - - -### persistence.treatRawStreamAsync(rawStream) ⇒ Promise.<{data: Array.<document>, indexes: Object.<string, rawIndex>}> -

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** - -- rawStream Readable - - - -### persistence.loadDatabase(callback) -

Load the database

-
    -
  1. Create all indexes
  2. -
  3. Insert all data
  4. -
  5. Compact the database
  6. -
-

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** - -- callback [NoParamCallback](#NoParamCallback) - - - -### persistence.loadDatabaseAsync() ⇒ Promise.<void> -

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.

- -**Kind**: static method of [Persistence](#Persistence) -**Params** - -- dir string -- [callback] [NoParamCallback](#NoParamCallback) = () => {} - - - -### Persistence.ensureDirectoryExistsAsync(dir) ⇒ Promise.<void> -

Async version of [ensureDirectoryExists](#Persistence.ensureDirectoryExists).

- -**Kind**: static method of [Persistence](#Persistence) -**See**: Persistence.ensureDirectoryExists -**Params** - -- dir string - - - -### ~~Persistence.getNWAppFilename(appName, relativeFilename) ⇒ string~~ -***Deprecated*** - -

Return the path the datafile if the given filename is relative to the directory where Node Webkit stores -data for this application. Probably the best place to store data

- -**Kind**: static method of [Persistence](#Persistence) -**Params** - -- appName string -- relativeFilename string - - - -### Persistence~treatRawStreamCallback : function -**Kind**: inner typedef of [Persistence](#Persistence) -**Params** - -- err Error -- data object - - .data [Array.<document>](#document) - - .indexes Object.<string, rawIndex> - diff --git a/docs/Waterfall.md b/docs/Waterfall.md deleted file mode 100644 index b253438..0000000 --- a/docs/Waterfall.md +++ /dev/null @@ -1,43 +0,0 @@ - - -## Waterfall -

Responsible for sequentially executing actions on the database

- -**Kind**: global class - -* [Waterfall](#Waterfall) - * [new Waterfall()](#new_Waterfall_new) - * [.guardian](#Waterfall+guardian) ⇒ Promise - * [.waterfall(func)](#Waterfall+waterfall) ⇒ [AsyncFunction](#AsyncFunction) - * [.chain(promise)](#Waterfall+chain) ⇒ Promise - - - -### new Waterfall() -

Instantiate a new Waterfall.

- - - -### waterfall.guardian ⇒ Promise -

Getter that gives a Promise which resolves when all tasks up to when this function is called are done.

-

This Promise cannot reject.

- -**Kind**: instance property of [Waterfall](#Waterfall) - - -### waterfall.waterfall(func) ⇒ [AsyncFunction](#AsyncFunction) -**Kind**: instance method of [Waterfall](#Waterfall) -**Params** - -- func [AsyncFunction](#AsyncFunction) - - - -### waterfall.chain(promise) ⇒ Promise -

Shorthand for chaining a promise to the Waterfall

- -**Kind**: instance method of [Waterfall](#Waterfall) -**Params** - -- promise Promise - diff --git a/docs/byline.md b/docs/byline.md deleted file mode 100644 index 87c28a4..0000000 --- a/docs/byline.md +++ /dev/null @@ -1,10 +0,0 @@ - - -## byline - - -### byline.LineStream -

Fork from [https://github.com/jahewson/node-byline](https://github.com/jahewson/node-byline).

- -**Kind**: static class of [byline](#module_byline) -**See**: https://github.com/jahewson/node-byline diff --git a/docs/customUtilsBrowser.md b/docs/customUtilsBrowser.md deleted file mode 100644 index 3a931d0..0000000 --- a/docs/customUtilsBrowser.md +++ /dev/null @@ -1,34 +0,0 @@ - - -## customUtilsBrowser -

Utility functions that need to be reimplemented for each environment. -This is the version for the browser & React-Native

- - -* [customUtilsBrowser](#module_customUtilsBrowser) - * [~randomBytes(size)](#module_customUtilsBrowser..randomBytes) ⇒ array.<number> - * [~byteArrayToBase64(uint8)](#module_customUtilsBrowser..byteArrayToBase64) ⇒ string - - - -### customUtilsBrowser~randomBytes(size) ⇒ array.<number> -

Taken from the crypto-browserify module -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** - -- size number -

in bytes

- - - -### customUtilsBrowser~byteArrayToBase64(uint8) ⇒ string -

Taken from the base64-js module -https://github.com/beatgammit/base64-js/

- -**Kind**: inner method of [customUtilsBrowser](#module_customUtilsBrowser) -**Params** - -- uint8 array - diff --git a/docs/customUtilsNode.md b/docs/customUtilsNode.md deleted file mode 100644 index ec23df5..0000000 --- a/docs/customUtilsNode.md +++ /dev/null @@ -1,41 +0,0 @@ - - -## customUtilsNode -

Utility functions that need to be reimplemented for each environment. -This is the version for Node.js

- - -* [customUtilsNode](#module_customUtilsNode) - * [.uid(len)](#module_customUtilsNode.uid) ⇒ string - * [.uid(len)](#module_customUtilsNode.uid) ⇒ string - - - -### customUtilsNode.uid(len) ⇒ string -

Return a random alphanumerical string of length len -There is a very small probability (less than 1/1,000,000) for the length to be less than len -(il the base64 conversion yields too many pluses and slashes) but -that's not an issue here -The probability of a collision is extremely small (need 3*10^12 documents to have one chance in a million of a collision) -See http://en.wikipedia.org/wiki/Birthday_problem

- -**Kind**: static method of [customUtilsNode](#module_customUtilsNode) -**Params** - -- len number - - - -### customUtilsNode.uid(len) ⇒ string -

Return a random alphanumerical string of length len -There is a very small probability (less than 1/1,000,000) for the length to be less than len -(il the base64 conversion yields too many pluses and slashes) but -that's not an issue here -The probability of a collision is extremely small (need 3*10^12 documents to have one chance in a million of a collision) -See http://en.wikipedia.org/wiki/Birthday_problem

- -**Kind**: static method of [customUtilsNode](#module_customUtilsNode) -**Params** - -- len number - diff --git a/docs/globals.md b/docs/globals.md deleted file mode 100644 index b1a8a76..0000000 --- a/docs/globals.md +++ /dev/null @@ -1,155 +0,0 @@ - - -## 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:

- - -**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 beforeDeserializationand 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 deleted file mode 100644 index 5bd8153..0000000 --- a/docs/model.md +++ /dev/null @@ -1,206 +0,0 @@ - - -## model -

Handle models (i.e. docs) -Serialization/deserialization -Copying -Querying, update

- - -* [model](#module_model) - * _static_ - * [.checkObject(obj)](#module_model.checkObject) - * [.serialize(obj)](#module_model.serialize) ⇒ string - * [.deserialize(rawData)](#module_model.deserialize) ⇒ [document](#document) - * [.compareThings(a, b, [_compareStrings])](#module_model.compareThings) ⇒ number - * [.modify(obj, updateQuery)](#module_model.modify) ⇒ [document](#document) - * [.getDotValue(obj, field)](#module_model.getDotValue) ⇒ \* - * [.areThingsEqual(a, a)](#module_model.areThingsEqual) ⇒ boolean - * [.match(obj, query)](#module_model.match) ⇒ boolean - * _inner_ - * [~modifierFunctions](#module_model..modifierFunctions) : enum - * [~comparisonFunctions](#module_model..comparisonFunctions) : enum - * [~logicalOperators](#module_model..logicalOperators) - * [~modifierFunction](#module_model..modifierFunction) : function - * [~comparisonOperator](#module_model..comparisonOperator) ⇒ boolean - * [~whereCallback](#module_model..whereCallback) ⇒ boolean - - - -### model.checkObject(obj) -

Check a DB object and throw an error if it's not valid -Works by applying the above checkKey function to all fields recursively

- -**Kind**: static method of [model](#module_model) -**Params** - -- obj [document](#document) | [Array.<document>](#document) - - - -### model.serialize(obj) ⇒ string -

Serialize an object to be persisted to a one-line string -For serialization/deserialization, we use the native JSON parser and not eval or Function -That gives us less freedom but data entered in the database may come from users -so eval and the like are not safe -Accepted primitive types: Number, String, Boolean, Date, null -Accepted secondary types: Objects, Arrays

- -**Kind**: static method of [model](#module_model) -**Params** - -- obj [document](#document) - - - -### model.deserialize(rawData) ⇒ [document](#document) -

From a one-line representation of an object generate by the serialize function -Return the object itself

- -**Kind**: static method of [model](#module_model) -**Params** - -- rawData string - - - -### model.compareThings(a, b, [_compareStrings]) ⇒ number -

Compare { things U undefined } -Things are defined as any native types (string, number, boolean, null, date) and objects -We need to compare with undefined as it will be used in indexes -In the case of objects and arrays, we deep-compare -If two objects dont have the same type, the (arbitrary) type hierarchy is: undefined, null, number, strings, boolean, dates, arrays, objects -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** - -- a \* -- b \* -- [_compareStrings] [compareStrings](#compareStrings) -

String comparing function, returning -1, 0 or 1, overriding default string comparison (useful for languages with accented letters)

- - - -### model.modify(obj, updateQuery) ⇒ [document](#document) -

Modify a DB object according to an update query

- -**Kind**: static method of [model](#module_model) -**Params** - -- obj [document](#document) -- updateQuery [query](#query) - - - -### model.getDotValue(obj, field) ⇒ \* -

Get a value from object with dot notation

- -**Kind**: static method of [model](#module_model) -**Params** - -- obj object -- field string - - - -### model.areThingsEqual(a, a) ⇒ boolean -

Check whether 'things' are equal -Things are defined as any native types (string, number, boolean, null, date) and objects -In the case of object, we check deep equality -Returns true if they are, false otherwise

- -**Kind**: static method of [model](#module_model) -**Params** - -- a \* -- a \* - - - -### model.match(obj, query) ⇒ boolean -

Tell if a given document matches a query

- -**Kind**: static method of [model](#module_model) -**Params** - -- obj [document](#document) -

Document to check

-- query [query](#query) - - - -### model~modifierFunctions : enum -**Kind**: inner enum of [model](#module_model) -**Properties** - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| $set | modifierFunction | |

Set a field to a new value

| -| $unset | modifierFunction | |

Unset a field

| -| $min | modifierFunction | |

Updates the value of the field, only if specified field is smaller than the current value of the field

| -| $max | modifierFunction | |

Updates the value of the field, only if specified field is greater than the current value of the field

| -| $inc | modifierFunction | |

Increment a numeric field's value

| -| $pull | modifierFunction | |

Removes all instances of a value from an existing array

| -| $pop | modifierFunction | |

Remove the first or last element of an array

| -| $addToSet | modifierFunction | |

Add an element to an array field only if it is not already in it No modification if the element is already in the array Note that it doesn't check whether the original array contains duplicates

| -| $push | modifierFunction | |

Push an element to the end of an array field Optional modifier $each instead of value to push several values Optional modifier $slice to slice the resulting array, see https://docs.mongodb.org/manual/reference/operator/update/slice/ Difference with MongoDB: if $slice is specified and not $each, we act as if value is an empty array

| - - - -### model~comparisonFunctions : enum -**Kind**: inner enum of [model](#module_model) -**Properties** - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| $lt | comparisonOperator | |

Lower than

| -| $lte | comparisonOperator | |

Lower than or equals

| -| $gt | comparisonOperator | |

Greater than

| -| $gte | comparisonOperator | |

Greater than or equals

| -| $ne | comparisonOperator | |

Does not equal

| -| $in | comparisonOperator | |

Is in Array

| -| $nin | comparisonOperator | |

Is not in Array

| -| $regex | comparisonOperator | |

Matches Regexp

| -| $exists | comparisonOperator | |

Returns true if field exists

| -| $size | comparisonOperator | |

Specific to Arrays, returns true if a length equals b

| -| $elemMatch | comparisonOperator | |

Specific to Arrays, returns true if some elements of a match the query b

| - - - -### model~logicalOperators -**Kind**: inner enum of [model](#module_model) -**Properties** - -| Name | Default | Description | -| --- | --- | --- | -| $or | |

Match any of the subqueries

| -| $and | |

Match all of the subqueries

| -| $not | |

Inverted match of the query

| -| $where | |

Use a function to match

| - - - -### model~modifierFunction : function -**Kind**: inner typedef of [model](#module_model) -**Params** - -- 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** - -- a \* -

Value in the object

-- b \* -

Value in the query

- - - -### model~whereCallback ⇒ boolean -**Kind**: inner typedef of [model](#module_model) -**Params** - -- obj [document](#document) - diff --git a/docs/storage.md b/docs/storage.md deleted file mode 100644 index 86d9525..0000000 --- a/docs/storage.md +++ /dev/null @@ -1,360 +0,0 @@ - - -## storage -

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) - * _static_ - * [.exists(file, cb)](#module_storage.exists) - * [.existsAsync(file)](#module_storage.existsAsync) ⇒ Promise.<boolean> - * [.rename(oldPath, newPath, c)](#module_storage.rename) ⇒ void - * [.renameAsync(oldPath, newPath)](#module_storage.renameAsync) ⇒ Promise.<void> - * [.writeFile(path, data, options, callback)](#module_storage.writeFile) - * [.writeFileAsync(path, data, [options])](#module_storage.writeFileAsync) ⇒ Promise.<void> - * [.writeFileStream(path, [options])](#module_storage.writeFileStream) ⇒ fs.WriteStream - * [.unlink(path, callback)](#module_storage.unlink) - * [.unlinkAsync(path)](#module_storage.unlinkAsync) ⇒ Promise.<void> - * [.appendFile(path, data, options, callback)](#module_storage.appendFile) - * [.appendFileAsync(path, data, [options])](#module_storage.appendFileAsync) ⇒ Promise.<void> - * [.readFile(path, options, callback)](#module_storage.readFile) - * [.readFileAsync(path, [options])](#module_storage.readFileAsync) ⇒ Promise.<Buffer> - * [.readFileStream(path, [options])](#module_storage.readFileStream) ⇒ fs.ReadStream - * [.mkdir(path, options, callback)](#module_storage.mkdir) - * [.mkdirAsync(path, options)](#module_storage.mkdirAsync) ⇒ Promise.<(void\|string)> - * [.ensureFileDoesntExistAsync(file)](#module_storage.ensureFileDoesntExistAsync) ⇒ Promise.<void> - * [.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) - * [.writeFileLinesAsync(filename, lines)](#module_storage.writeFileLinesAsync) ⇒ Promise.<void> - * [.crashSafeWriteFileLines(filename, lines, [callback])](#module_storage.crashSafeWriteFileLines) - * [.crashSafeWriteFileLinesAsync(filename, lines)](#module_storage.crashSafeWriteFileLinesAsync) ⇒ Promise.<void> - * [.ensureDatafileIntegrity(filename, callback)](#module_storage.ensureDatafileIntegrity) - * [.ensureDatafileIntegrityAsync(filename)](#module_storage.ensureDatafileIntegrityAsync) ⇒ Promise.<void> - * _inner_ - * [~existsCallback](#module_storage..existsCallback) : function - - - -### storage.exists(file, cb) -

Callback returns true if file exists.

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- file string -- cb [existsCallback](#module_storage..existsCallback) - - - -### storage.existsAsync(file) ⇒ Promise.<boolean> -

Async version of [exists](#module_storage.exists).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.exists -**Params** - -- file string - - - -### storage.rename(oldPath, newPath, c) ⇒ void -

Node.js' [fs.rename](https://nodejs.org/api/fs.html#fsrenameoldpath-newpath-callback).

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- oldPath string -- newPath string -- c [NoParamCallback](#NoParamCallback) - - - -### storage.renameAsync(oldPath, newPath) ⇒ Promise.<void> -

Async version of [rename](#module_storage.rename).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.rename -**Params** - -- oldPath string -- newPath string - - - -### storage.writeFile(path, data, options, callback) -

Node.js' [fs.writeFile](https://nodejs.org/api/fs.html#fswritefilefile-data-options-callback).

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- path string -- data string -- options object -- callback function - - - -### storage.writeFileAsync(path, data, [options]) ⇒ Promise.<void> -

Async version of [writeFile](#module_storage.writeFile).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.writeFile -**Params** - -- path string -- data string -- [options] object - - - -### storage.writeFileStream(path, [options]) ⇒ fs.WriteStream -

Node.js' [fs.createWriteStream](https://nodejs.org/api/fs.html#fscreatewritestreampath-options).

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- path string -- [options] Object - - - -### storage.unlink(path, callback) -

Node.js' [fs.unlink](https://nodejs.org/api/fs.html#fsunlinkpath-callback).

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- path string -- callback function - - - -### storage.unlinkAsync(path) ⇒ Promise.<void> -

Async version of [unlink](#module_storage.unlink).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.unlink -**Params** - -- path string - - - -### storage.appendFile(path, data, options, callback) -

Node.js' [fs.appendFile](https://nodejs.org/api/fs.html#fsappendfilepath-data-options-callback).

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- path string -- data string -- options object -- callback function - - - -### storage.appendFileAsync(path, data, [options]) ⇒ Promise.<void> -

Async version of [appendFile](#module_storage.appendFile).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.appendFile -**Params** - -- path string -- data string -- [options] object - - - -### storage.readFile(path, options, callback) -

Node.js' [fs.readFile](https://nodejs.org/api/fs.html#fsreadfilepath-options-callback)

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- path string -- options object -- callback function - - - -### storage.readFileAsync(path, [options]) ⇒ Promise.<Buffer> -

Async version of [readFile](#module_storage.readFile).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.readFile -**Params** - -- path string -- [options] object - - - -### storage.readFileStream(path, [options]) ⇒ fs.ReadStream -

Node.js' [fs.createReadStream](https://nodejs.org/api/fs.html#fscreatereadstreampath-options).

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- path string -- [options] Object - - - -### storage.mkdir(path, options, callback) -

Node.js' [fs.mkdir](https://nodejs.org/api/fs.html#fsmkdirpath-options-callback).

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- path string -- options object -- callback function - - - -### storage.mkdirAsync(path, options) ⇒ Promise.<(void\|string)> -

Async version of [mkdir](#module_storage.mkdir).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.mkdir -**Params** - -- 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** - -- file string - - - -### storage.ensureFileDoesntExist(file, callback) -

Removes file if it exists.

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- file string -- callback [NoParamCallback](#NoParamCallback) - - - -### storage.flushToStorage(options, callback) -

Flush data in OS buffer to storage if corresponding option is set.

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- 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> -

Async version of [flushToStorage](#module_storage.flushToStorage).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.flushToStorage -**Params** - -- options object | string - - [.filename] string - - [.isDir] boolean = false - - - -### storage.writeFileLines(filename, lines, [callback]) -

Fully write or rewrite the datafile.

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- filename string -- lines Array.<string> -- [callback] [NoParamCallback](#NoParamCallback) = () => {} - - - -### storage.writeFileLinesAsync(filename, lines) ⇒ Promise.<void> -

Async version of [writeFileLines](#module_storage.writeFileLines).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.writeFileLines -**Params** - -- 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).

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- filename string -- lines Array.<string> -- [callback] [NoParamCallback](#NoParamCallback) -

Optional callback, signature: err

- - - -### storage.crashSafeWriteFileLinesAsync(filename, lines) ⇒ Promise.<void> -

Async version of [crashSafeWriteFileLines](#module_storage.crashSafeWriteFileLines).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.crashSafeWriteFileLines -**Params** - -- 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.

- -**Kind**: static method of [storage](#module_storage) -**Params** - -- filename string -- callback [NoParamCallback](#NoParamCallback) -

signature: err

- - - -### storage.ensureDatafileIntegrityAsync(filename) ⇒ Promise.<void> -

Async version of [ensureDatafileIntegrity](#module_storage.ensureDatafileIntegrity).

- -**Kind**: static method of [storage](#module_storage) -**See**: module:storage.ensureDatafileIntegrity -**Params** - -- filename string - - - -### storage~existsCallback : function -**Kind**: inner typedef of [storage](#module_storage) -**Params** - -- exists boolean - diff --git a/docs/storageBrowser.md b/docs/storageBrowser.md deleted file mode 100644 index 343cdfe..0000000 --- a/docs/storageBrowser.md +++ /dev/null @@ -1,256 +0,0 @@ - - -## storageBrowser -

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) - * _static_ - * [.existsAsync(file)](#module_storageBrowser.existsAsync) ⇒ Promise.<boolean> - * [.exists(file, cb)](#module_storageBrowser.exists) - * [.renameAsync(oldPath, newPath)](#module_storageBrowser.renameAsync) ⇒ Promise.<void> - * [.rename(oldPath, newPath, c)](#module_storageBrowser.rename) ⇒ void - * [.writeFileAsync(file, data, [options])](#module_storageBrowser.writeFileAsync) ⇒ Promise.<void> - * [.writeFile(path, data, options, callback)](#module_storageBrowser.writeFile) - * [.appendFileAsync(filename, toAppend, [options])](#module_storageBrowser.appendFileAsync) ⇒ Promise.<void> - * [.appendFile(filename, toAppend, [options], callback)](#module_storageBrowser.appendFile) - * [.readFileAsync(filename, [options])](#module_storageBrowser.readFileAsync) ⇒ Promise.<Buffer> - * [.readFile(filename, options, callback)](#module_storageBrowser.readFile) - * [.unlinkAsync(filename)](#module_storageBrowser.unlinkAsync) ⇒ Promise.<void> - * [.unlink(path, callback)](#module_storageBrowser.unlink) - * [.mkdirAsync(path, [options])](#module_storageBrowser.mkdirAsync) ⇒ Promise.<(void\|string)> - * [.mkdir(path, options, callback)](#module_storageBrowser.mkdir) - * [.ensureDatafileIntegrityAsync(filename)](#module_storageBrowser.ensureDatafileIntegrityAsync) ⇒ Promise.<void> - * [.ensureDatafileIntegrity(filename, callback)](#module_storageBrowser.ensureDatafileIntegrity) - * [.crashSafeWriteFileLinesAsync(filename, lines)](#module_storageBrowser.crashSafeWriteFileLinesAsync) ⇒ Promise.<void> - * [.crashSafeWriteFileLines(filename, lines, [callback])](#module_storageBrowser.crashSafeWriteFileLines) - * _inner_ - * [~existsCallback](#module_storageBrowser..existsCallback) : function - - - -### storageBrowser.existsAsync(file) ⇒ Promise.<boolean> -

Returns Promise if file exists.

-

Async version of [exists](#module_storageBrowser.exists).

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**See**: module:storageBrowser.exists -**Params** - -- file string - - - -### storageBrowser.exists(file, cb) -

Callback returns true if file exists.

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**Params** - -- file string -- cb [existsCallback](#module_storageBrowser..existsCallback) - - - -### storageBrowser.renameAsync(oldPath, newPath) ⇒ Promise.<void> -

Async version of [rename](#module_storageBrowser.rename).

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**See**: module:storageBrowser.rename -**Params** - -- oldPath string -- newPath string - - - -### storageBrowser.rename(oldPath, newPath, c) ⇒ void -

Moves the item from one path to another

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**Params** - -- oldPath string -- newPath string -- c [NoParamCallback](#NoParamCallback) - - - -### storageBrowser.writeFileAsync(file, data, [options]) ⇒ Promise.<void> -

Async version of [writeFile](#module_storageBrowser.writeFile).

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**See**: module:storageBrowser.writeFile -**Params** - -- file string -- data string -- [options] object - - - -### storageBrowser.writeFile(path, data, options, callback) -

Saves the item at given path

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**Params** - -- path string -- data string -- options object -- callback function - - - -### storageBrowser.appendFileAsync(filename, toAppend, [options]) ⇒ Promise.<void> -

Async version of [appendFile](#module_storageBrowser.appendFile).

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**See**: module:storageBrowser.appendFile -**Params** - -- filename string -- toAppend string -- [options] object - - - -### storageBrowser.appendFile(filename, toAppend, [options], callback) -

Append to the item at given path

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**Params** - -- filename string -- toAppend string -- [options] object -- callback function - - - -### storageBrowser.readFileAsync(filename, [options]) ⇒ Promise.<Buffer> -

Async version of [readFile](#module_storageBrowser.readFile).

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**See**: module:storageBrowser.readFile -**Params** - -- filename string -- [options] object - - - -### storageBrowser.readFile(filename, options, callback) -

Read data at given path

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**Params** - -- filename string -- options object -- callback function - - - -### storageBrowser.unlinkAsync(filename) ⇒ Promise.<void> -

Async version of [unlink](#module_storageBrowser.unlink).

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**See**: module:storageBrowser.unlink -**Params** - -- filename string - - - -### storageBrowser.unlink(path, callback) -

Remove the data at given path

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**Params** - -- path string -- callback function - - - -### storageBrowser.mkdirAsync(path, [options]) ⇒ Promise.<(void\|string)> -

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** - -- path string -- [options] object - - - -### storageBrowser.mkdir(path, options, callback) -

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** - -- path string -- options object -- callback function - - - -### storageBrowser.ensureDatafileIntegrityAsync(filename) ⇒ Promise.<void> -

Shim for [ensureDatafileIntegrityAsync](#module_storage.ensureDatafileIntegrityAsync), nothing to do, no data corruption possible in the browser.

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**Params** - -- filename string - - - -### storageBrowser.ensureDatafileIntegrity(filename, callback) -

Shim for [ensureDatafileIntegrity](#module_storage.ensureDatafileIntegrity), nothing to do, no data corruption possible in the browser.

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**Params** - -- filename string -- callback [NoParamCallback](#NoParamCallback) -

signature: err

- - - -### storageBrowser.crashSafeWriteFileLinesAsync(filename, lines) ⇒ Promise.<void> -

Async version of [crashSafeWriteFileLines](#module_storageBrowser.crashSafeWriteFileLines).

- -**Kind**: static method of [storageBrowser](#module_storageBrowser) -**See**: module:storageBrowser.crashSafeWriteFileLines -**Params** - -- filename string -- lines Array.<string> - - - -### storageBrowser.crashSafeWriteFileLines(filename, lines, [callback]) -

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** - -- filename string -- lines Array.<string> -- [callback] [NoParamCallback](#NoParamCallback) -

Optional callback, signature: err

- - - -### storageBrowser~existsCallback : function -**Kind**: inner typedef of [storageBrowser](#module_storageBrowser) -**Params** - -- exists boolean - diff --git a/docs/storageReactNative.md b/docs/storageReactNative.md deleted file mode 100644 index 68dc403..0000000 --- a/docs/storageReactNative.md +++ /dev/null @@ -1,255 +0,0 @@ - - -## storageReactNative -

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) - * _static_ - * [.existsAsync(file)](#module_storageReactNative.existsAsync) ⇒ Promise.<boolean> - * [.exists(file, cb)](#module_storageReactNative.exists) - * [.renameAsync(oldPath, newPath)](#module_storageReactNative.renameAsync) ⇒ Promise.<void> - * [.rename(oldPath, newPath, c)](#module_storageReactNative.rename) ⇒ void - * [.writeFileAsync(file, data, [options])](#module_storageReactNative.writeFileAsync) ⇒ Promise.<void> - * [.writeFile(path, data, options, callback)](#module_storageReactNative.writeFile) - * [.appendFileAsync(filename, toAppend, [options])](#module_storageReactNative.appendFileAsync) ⇒ Promise.<void> - * [.appendFile(filename, toAppend, [options], callback)](#module_storageReactNative.appendFile) - * [.readFileAsync(filename, [options])](#module_storageReactNative.readFileAsync) ⇒ Promise.<string> - * [.readFile(filename, options, callback)](#module_storageReactNative.readFile) - * [.unlinkAsync(filename)](#module_storageReactNative.unlinkAsync) ⇒ Promise.<void> - * [.unlink(path, callback)](#module_storageReactNative.unlink) - * [.mkdirAsync(dir, [options])](#module_storageReactNative.mkdirAsync) ⇒ Promise.<(void\|string)> - * [.mkdir(path, options, callback)](#module_storageReactNative.mkdir) - * [.ensureDatafileIntegrityAsync(filename)](#module_storageReactNative.ensureDatafileIntegrityAsync) ⇒ Promise.<void> - * [.ensureDatafileIntegrity(filename, callback)](#module_storageReactNative.ensureDatafileIntegrity) - * [.crashSafeWriteFileLinesAsync(filename, lines)](#module_storageReactNative.crashSafeWriteFileLinesAsync) ⇒ Promise.<void> - * [.crashSafeWriteFileLines(filename, lines, [callback])](#module_storageReactNative.crashSafeWriteFileLines) - * _inner_ - * [~existsCallback](#module_storageReactNative..existsCallback) : function - - - -### storageReactNative.existsAsync(file) ⇒ Promise.<boolean> -

Async version of [exists](#module_storageReactNative.exists).

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**See**: module:storageReactNative.exists -**Params** - -- file string - - - -### storageReactNative.exists(file, cb) -

Callback returns true if file exists

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**Params** - -- file string -- cb [existsCallback](#module_storageReactNative..existsCallback) - - - -### storageReactNative.renameAsync(oldPath, newPath) ⇒ Promise.<void> -

Async version of [rename](#module_storageReactNative.rename).

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**See**: module:storageReactNative.rename -**Params** - -- oldPath string -- newPath string - - - -### storageReactNative.rename(oldPath, newPath, c) ⇒ void -

Moves the item from one path to another

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**Params** - -- oldPath string -- newPath string -- c [NoParamCallback](#NoParamCallback) - - - -### storageReactNative.writeFileAsync(file, data, [options]) ⇒ Promise.<void> -

Async version of [writeFile](#module_storageReactNative.writeFile).

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**See**: module:storageReactNative.writeFile -**Params** - -- file string -- data string -- [options] object - - - -### storageReactNative.writeFile(path, data, options, callback) -

Saves the item at given path

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**Params** - -- path string -- data string -- options object -- callback function - - - -### storageReactNative.appendFileAsync(filename, toAppend, [options]) ⇒ Promise.<void> -

Async version of [appendFile](#module_storageReactNative.appendFile).

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**See**: module:storageReactNative.appendFile -**Params** - -- filename string -- toAppend string -- [options] object - - - -### storageReactNative.appendFile(filename, toAppend, [options], callback) -

Append to the item at given path

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**Params** - -- filename string -- toAppend string -- [options] object -- callback function - - - -### storageReactNative.readFileAsync(filename, [options]) ⇒ Promise.<string> -

Async version of [readFile](#module_storageReactNative.readFile).

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**See**: module:storageReactNative.readFile -**Params** - -- filename string -- [options] object - - - -### storageReactNative.readFile(filename, options, callback) -

Read data at given path

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**Params** - -- filename string -- options object -- callback function - - - -### storageReactNative.unlinkAsync(filename) ⇒ Promise.<void> -

Async version of [unlink](#module_storageReactNative.unlink).

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**See**: module:storageReactNative.unlink -**Params** - -- filename string - - - -### storageReactNative.unlink(path, callback) -

Remove the data at given path

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**Params** - -- path string -- callback function - - - -### storageReactNative.mkdirAsync(dir, [options]) ⇒ Promise.<(void\|string)> -

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** - -- dir string -- [options] object - - - -### storageReactNative.mkdir(path, options, callback) -

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** - -- path string -- options object -- callback function - - - -### storageReactNative.ensureDatafileIntegrityAsync(filename) ⇒ Promise.<void> -

Shim for [ensureDatafileIntegrityAsync](#module_storage.ensureDatafileIntegrityAsync), nothing to do, no data corruption possible in the browser.

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**Params** - -- filename string - - - -### storageReactNative.ensureDatafileIntegrity(filename, callback) -

Shim for [ensureDatafileIntegrity](#module_storage.ensureDatafileIntegrity), nothing to do, no data corruption possible in the browser.

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**Params** - -- filename string -- callback [NoParamCallback](#NoParamCallback) -

signature: err

- - - -### storageReactNative.crashSafeWriteFileLinesAsync(filename, lines) ⇒ Promise.<void> -

Async version of [crashSafeWriteFileLines](#module_storageReactNative.crashSafeWriteFileLines).

- -**Kind**: static method of [storageReactNative](#module_storageReactNative) -**See**: module:storageReactNative.crashSafeWriteFileLines -**Params** - -- filename string -- lines Array.<string> - - - -### storageReactNative.crashSafeWriteFileLines(filename, lines, [callback]) -

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** - -- filename string -- lines Array.<string> -- [callback] [NoParamCallback](#NoParamCallback) -

Optional callback, signature: err

- - - -### storageReactNative~existsCallback : function -**Kind**: inner typedef of [storageReactNative](#module_storageReactNative) -**Params** - -- exists boolean - diff --git a/docs/utils.md b/docs/utils.md deleted file mode 100644 index c04794b..0000000 --- a/docs/utils.md +++ /dev/null @@ -1,64 +0,0 @@ - - -## utils -

Utility functions for all environments. -This replaces the underscore dependency.

- - -* [utils](#module_utils) - * _static_ - * [.uniq(array, [iteratee])](#module_utils.uniq) ⇒ Array - * [.isDate(d)](#module_utils.isDate) ⇒ boolean - * [.isRegExp(re)](#module_utils.isRegExp) ⇒ boolean - * _inner_ - * [~isObject(arg)](#module_utils..isObject) ⇒ boolean - - - -### 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](https://underscorejs.org/#uniq).

- -**Kind**: static method of [utils](#module_utils) -**Params** - -- 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](https://underscorejs.org/#isDate).

- -**Kind**: static method of [utils](#module_utils) -**Params** - -- d \* - - - -### utils.isRegExp(re) ⇒ boolean -

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** - -- 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](https://underscorejs.org/#isObject).

- -**Kind**: inner method of [utils](#module_utils) -**Params** - -- arg \* - diff --git a/jsdoc2md.js b/jsdoc2md.js deleted file mode 100644 index 0cf2085..0000000 --- a/jsdoc2md.js +++ /dev/null @@ -1,67 +0,0 @@ -'use strict' -const jsdoc2md = require('jsdoc-to-markdown') -const fs = require('fs') -const path = require('path') - -const jsdocConf = './jsdoc.conf.js' - -/* output path */ -const outputDir = './docs' - -const getJsdocDataOptions = { - /* same input path as jsdoc */ - files: require(jsdocConf).source.include, - configure: jsdocConf, - 'no-cache': true -} - -const renderOptions = { - 'param-list-format': 'list' -} - -fs.rmdirSync(outputDir, { recursive: true }) // clean docs dir -fs.mkdirSync(outputDir) // make docs dir - -/* get template data */ -const templateData = jsdoc2md.getTemplateDataSync(getJsdocDataOptions) - -/* reduce templateData to an array of class names */ -const classNames = templateData - .filter(({ kind, access }) => kind === 'class' && access !== 'private') - .map(({ name }) => name) - .filter(name => name !== 'LineStream') // it is a module that exports a class, dirty hack to hardcode this, but it works - -const moduleNames = templateData - .filter(({ kind, access }) => kind === 'module' && access !== 'private') - .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({ ...renderOptions, data: templateData, template: template }) - fs.writeFileSync(path.resolve(outputDir, `${className}.md`), output) -} - -/* create a documentation file for each module */ -for (const moduleName of moduleNames) { - const template = `{{#module name="${moduleName}"}}{{>docs}}{{/module}}` - console.log(`rendering ${moduleName}, 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 87a583c..dfe32f3 100755 --- a/lib/cursor.js +++ b/lib/cursor.js @@ -247,4 +247,7 @@ class Cursor { } // Interface +/** + * @type {Cursor} + */ module.exports = Cursor diff --git a/lib/datastore.js b/lib/datastore.js index 36e9f81..bea4c7d 100755 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -13,7 +13,7 @@ const { isDate } = require('./utils.js') // TODO: check the classes and modules which need to be included int he documentation // TODO: replace examples of the Readme with @example JSDoc tags // TODO: update changelog - +// TODO: dropDatabase callback + tests /** * Callback with no parameter * @callback NoParamCallback @@ -140,8 +140,16 @@ const { isDate } = require('./utils.js') */ /** - * The `Datastore` class is the main class of NeDB. - * @extends EventEmitter + * @external EventEmitter + * @see http://nodejs.org/api/events.html + */ + +/** + * @class + * @classdesc The `Datastore` class is the main class of NeDB. + * @extends external:EventEmitter + * @emits Datastore#event:"compaction.done" + * @typicalname NeDB */ class Datastore extends EventEmitter { /** @@ -188,8 +196,6 @@ class Datastore extends EventEmitter { * @param {compareStrings} [options.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. - * - * @fires Datastore#event:"compaction.done" */ constructor (options) { super() diff --git a/package.json b/package.json index 83d6d40..8e43458 100755 --- a/package.json +++ b/package.json @@ -87,7 +87,7 @@ "test:react-native": "jest test/react-native", "test:typings": "ts-node ./typings-tests.ts", "prepublishOnly": "npm run build:browser", - "generateDocs:markdown": "node jsdoc2md.js", + "generateDocs:markdown": "jsdoc2md --no-cache -c jsdoc.conf.js --param-list-format list --files . > API.md", "generateDocs:html": "jsdoc -c jsdoc.conf.js -d docs-html --readme README.md" }, "main": "index.js",