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

Persistence handles the compaction exposed in the Datastore [compactDatafileAsync](#Datastore+compactDatafileAsync), [setAutocompactionInterval](#Datastore+setAutocompactionInterval).

Since version 3.0.0, using [Datastore.persistence](Datastore.persistence) methods manually is deprecated.

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 for the given Cursor.

**Kind**: instance method of [Cursor](#Cursor) **Returns**: [Cursor](#Cursor) -

the same instance of Cursor, (useful for chaining).

**Params** - limit Number ### cursor.skip(skip) ⇒ [Cursor](#Cursor)

Skip a number of results for the given Cursor.

**Kind**: instance method of [Cursor](#Cursor) **Returns**: [Cursor](#Cursor) -

the same instance of Cursor, (useful for chaining).

**Params** - skip Number ### cursor.sort(sortQuery) ⇒ [Cursor](#Cursor)

Sort results of the query for the given Cursor.

**Kind**: instance method of [Cursor](#Cursor) **Returns**: [Cursor](#Cursor) -

the same instance of Cursor, (useful for chaining).

**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 to the given Cursor.

**Kind**: instance method of [Cursor](#Cursor) **Returns**: [Cursor](#Cursor) -

the same instance of Cursor, (useful for chaining).

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

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

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

Get all matching elements. Will return pointers to matched elements (shallow copies), returning full copies is the role of [findAsync](#Datastore+findAsync) or [findOneAsync](#Datastore+findOneAsync).

**Kind**: instance method of [Cursor](#Cursor) ### 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 a 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) * [.compactDatafileAsync()](#Datastore+compactDatafileAsync) * [.compactDatafile([callback])](#Datastore+compactDatafile) * [.setAutocompactionInterval(interval)](#Datastore+setAutocompactionInterval) * [.stopAutocompaction()](#Datastore+stopAutocompaction) * [.loadDatabase([callback])](#Datastore+loadDatabase) * [.dropDatabaseAsync()](#Datastore+dropDatabaseAsync) ⇒ Promise * [.dropDatabase([callback])](#Datastore+dropDatabase) * [.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> * [.insert(newDoc, [callback])](#Datastore+insert) * [.insertAsync(newDoc)](#Datastore+insertAsync) ⇒ Promise.<(document\|Array.<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|], [callback])](#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](#Datastore), any [Cursor](#Cursor) produced by the Datastore and by [compactDatafileAsync](#Datastore+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.compactDatafileAsync()

Queue a compaction/rewrite of the datafile. It works by rewriting the database file, and compacts it 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.

**Kind**: instance method of [Datastore](#Datastore) ### neDB.compactDatafile([callback])

Callback version of [compactDatafileAsync](#Datastore+compactDatafileAsync).

**Kind**: instance method of [Datastore](#Datastore) **See**: Datastore#compactDatafileAsync **Params** - [callback] [NoParamCallback](#NoParamCallback) = () => {} ### neDB.setAutocompactionInterval(interval)

Set automatic compaction every interval ms

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

in milliseconds, with an enforced minimum of 5000 milliseconds

### neDB.stopAutocompaction()

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

**Kind**: instance method of [Datastore](#Datastore) ### neDB.loadDatabase([callback])

Callback version of [loadDatabaseAsync](#Datastore+loadDatabaseAsync).

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

Stops auto-compaction, finishes all queued operations, drops the database both in memory and in storage. WARNING: it is not recommended re-using an instance of NeDB if its database has been dropped, it is preferable to instantiate a new one.

**Kind**: instance method of [Datastore](#Datastore) ### neDB.dropDatabase([callback])

Callback version of [dropDatabaseAsync](#Datastore+dropDatabaseAsync).

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

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

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

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

**Kind**: instance method of [Datastore](#Datastore) **See**: Datastore#ensureIndex **Params** - options object - .fieldName string - [.unique] boolean = false - [.sparse] boolean = false - [.expireAfterSeconds] number - [callback] [NoParamCallback](#NoParamCallback) ### neDB.ensureIndexAsync(options) ⇒ Promise.<void>

Ensure an index is kept for this field. Same parameters as lib/indexes This function acts synchronously on the indexes, however the persistence of the indexes is deferred with the executor.

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

### neDB.removeIndex(fieldName, [callback])

Callback version of [removeIndexAsync](#Datastore+removeIndexAsync).

**Kind**: instance method of [Datastore](#Datastore) **See**: Datastore#removeIndexAsync **Params** - fieldName string - [callback] [NoParamCallback](#NoParamCallback) ### neDB.removeIndexAsync(fieldName) ⇒ Promise.<void>

Remove an index.

**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.insert(newDoc, [callback])

Callback version of [insertAsync](#Datastore+insertAsync).

**Kind**: instance method of [Datastore](#Datastore) **See**: Datastore#insertAsync **Params** - newDoc [document](#document) | [Array.<document>](#document) - [callback] [SingleDocumentCallback](#SingleDocumentCallback) | [MultipleDocumentsCallback](#MultipleDocumentsCallback) ### neDB.insertAsync(newDoc) ⇒ Promise.<(document\|Array.<document>)>

Insert a new document, or new documents.

**Kind**: instance method of [Datastore](#Datastore) **Returns**: Promise.<(document\|Array.<document>)> -

The document(s) inserted.

**Params** - newDoc [document](#document) | [Array.<document>](#document) -

Document or array of documents to insert.

### neDB.count(query, [callback]) ⇒ Cursor.<number> \| undefined

Callback-version of [countAsync](#Datastore+countAsync).

**Kind**: instance method of [Datastore](#Datastore) **See**: Datastore#countAsync **Params** - query [query](#query) - [callback] [countCallback](#Datastore..countCallback) ### neDB.countAsync(query) ⇒ Cursor.<number>

Count all documents matching the query.

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

Callback version of [findAsync](#Datastore+findAsync).

**Kind**: instance method of [Datastore](#Datastore) **See**: Datastore#findAsync **Params** - query [query](#query) - [projection] [projection](#projection) | [MultipleDocumentsCallback](#MultipleDocumentsCallback) = {} - [callback] [MultipleDocumentsCallback](#MultipleDocumentsCallback) ### neDB.findAsync(query, [projection]) ⇒ Cursor.<Array.<document>>

Find all documents matching the query. We return the [Cursor](#Cursor) that the user can either await directly or use to can [limit](#Cursor+limit) or [skip](#Cursor+skip) before.

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

Callback version of [findOneAsync](#Datastore+findOneAsync).

**Kind**: instance method of [Datastore](#Datastore) **See**: Datastore#findOneAsync **Params** - query [query](#query) - [projection] [projection](#projection) | [SingleDocumentCallback](#SingleDocumentCallback) = {} - [callback] [SingleDocumentCallback](#SingleDocumentCallback) ### neDB.findOneAsync(query, projection) ⇒ [Cursor.<document>](#document)

Find one document matching the query. We return the [Cursor](#Cursor) that the user can either await directly or use to can [skip](#Cursor+skip) before.

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

MongoDB-style query

- projection [projection](#projection) -

MongoDB-style projection

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

Callback version of [updateAsync](#Datastore+updateAsync).

**Kind**: instance method of [Datastore](#Datastore) **See**: Datastore#updateAsync **Params** - query [query](#query) - update [document](#document) | \* - [options|] Object | [updateCallback](#Datastore..updateCallback) - [.multi] boolean = false - [.upsert] boolean = false - [.returnUpdatedDocs] boolean = false - [callback] [updateCallback](#Datastore..updateCallback) ### neDB.updateAsync(query, update, [options]) ⇒ Promise.<{numAffected: number, affectedDocuments: (Array.<document>\|document\|null), upsert: boolean}>

Update all docs matching query.

**Kind**: instance method of [Datastore](#Datastore) **Returns**: Promise.<{numAffected: number, affectedDocuments: (Array.<document>\|document\|null), upsert: boolean}> - **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])

Callback version of [removeAsync](#Datastore+removeAsync).

**Kind**: instance method of [Datastore](#Datastore) **See**: Datastore#removeAsync **Params** - query [query](#query) - [options] object | [removeCallback](#Datastore..removeCallback) = {} - [.multi] boolean = false - [cb] [removeCallback](#Datastore..removeCallback) = () => {} ### neDB.removeAsync(query, [options]) ⇒ Promise.<number>

Remove all docs matching the query.

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

How many documents were removed

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

MongoDB-style 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 [compactDatafileAsync](#Datastore+compactDatafileAsync), which is called periodically if you have called [setAutocompactionInterval](#Datastore+setAutocompactionInterval).

**Kind**: event emitted by [Datastore](#Datastore) ### Datastore~countCallback : function

Callback for [Datastore#countCallback](Datastore#countCallback).

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

See [updateAsync](#Datastore+updateAsync) return type for the definition of the callback parameters.

WARNING: Prior to 3.0.0, upsert was either true of falsy (but not false), it is now always a boolean. affectedDocuments could be undefined when returnUpdatedDocs was false, it is now null in these cases.

WARNING: Prior to 1.8.0, the upsert argument was not given, it was impossible for the developer to determine during a { multi: false, returnUpdatedDocs: true, upsert: true } update if it inserted a document or just updated it.

**Kind**: inner typedef of [Datastore](#Datastore) **See**: {Datastore#updateAsync} **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.

Persistence handles the compaction exposed in the Datastore [compactDatafileAsync](#Datastore+compactDatafileAsync), [setAutocompactionInterval](#Datastore+setAutocompactionInterval).

Since version 3.0.0, using [Datastore.persistence](Datastore.persistence) methods manually is deprecated.

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) * ~~[.compactDatafile([callback])](#Persistence+compactDatafile)~~ * ~~[.setAutocompactionInterval()](#Persistence+setAutocompactionInterval)~~ * ~~[.stopAutocompaction()](#Persistence+stopAutocompaction)~~ ### 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.compactDatafile([callback])~~ ***Deprecated*** **Kind**: instance method of [Persistence](#Persistence) **See** - Datastore#compactDatafile - Persistence#compactDatafileAsync **Params** - [callback] [NoParamCallback](#NoParamCallback) = () => {} ### ~~persistence.setAutocompactionInterval()~~ ***Deprecated*** **Kind**: instance method of [Persistence](#Persistence) **See**: Datastore#setAutocompactionInterval ### ~~persistence.stopAutocompaction()~~ ***Deprecated*** **Kind**: instance method of [Persistence](#Persistence) **See**: Datastore#stopAutocompaction ## 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 |