Skip to content
This repository has been archived by the owner on Aug 29, 2023. It is now read-only.

Latest commit

 

History

History
1056 lines (884 loc) · 28.7 KB

docs.md

File metadata and controls

1056 lines (884 loc) · 28.7 KB

Classes

Extension
Model
Encryption
SoftRemoves
Timestamps

Functions

augmenter(defaults)function
converter(__class)function
datastore(__class)Proxy.<Datastore>
encrypter(algorithm, password)function
decrypter(algorithm, password)function

Extension

Kind: global class

extension.apply() ⇒ boolean

This is called when the extension is beind applied.

Kind: instance method of Extension
Example

// check out the Timestamps or SoftRemoves extension...
// https://github.com/bajankristof/nedb-models/blob/master/src/extensions/Timestamps.js
// https://github.com/bajankristof/nedb-models/blob/master/src/extensions/SoftRemoves.js

extension.set(key, value, fn) ⇒ this

Set a non-static property or method.

Kind: instance method of Extension

ParamTypeDescription
keystring

The name of the property or method.

value* | function

The value to replace it with or a replacer function.

fnboolean

Whether to use the value as a replacer or not.

Example

// in apply() { ... }
this.set('one', 1)
// now the applied model has an instance property 'one' with a value of 1

Example

// in apply() { ... }
this.set('one', function () { return 1 })
// now the applied model has an instance method 'one' with a return value of 1

Example

// in apply() { ... } if you want to override an instance method
this.set('save', save => {
    return function () {
        console.log('we disabled saving')
        return this // the model instance
    }
})

extension.extend(key, value) ⇒ this

Extend a non-static property.

Kind: instance method of Extension

ParamTypeDescription
keystring

The name of the property.

valueObject

The value to extend it with.

extension.setStatic(key, value, fn) ⇒ this

Set a static property or method. (Works the same way extension.set does...)

Kind: instance method of Extension

ParamTypeDescription
keystring

The name of the static property or method.

value* | function

The value to replace it with or a replacer function.

fnboolean

Whether to use the value as a replacer or not.

Example

// in apply() { ... } if you want to override a static method
// first we need to reference the currently processed class
let __class = this.__class
this.setStatic('find', find => {
    return function (query) {
        console.log('we disabled the projection parameter')
        return find.call(__class, query)
    }
})

extension.extendStatic(key, value) ⇒ this

Extend a static property.

Kind: instance method of Extension

ParamTypeDescription
keystring

The name of the static property.

valueObject

The value to extend it with.

extension.extendDefaults(value) ⇒ this

Extend the value returned by the defaults static method of the model.

Kind: instance method of Extension

ParamTypeDescription
valueObject

The value to extend it with.

Example

// in apply() { ... }
this.extendDefaults({ query: { removedAt: null }})
// now the applied model class' static defaults() return value is 
// extended with the above object

extension.extendQuery(value) ⇒ this

Extend the default query. (Model.defaults().query)

Kind: instance method of Extension

ParamTypeDescription
valueObject

The value to extend it with.

extension.extendProjection(value) ⇒ this

Extend the default projection. (Model.defaults().projection)

Kind: instance method of Extension

ParamTypeDescription
valueObject

The value to extend it with.

extension.extendValues(value) ⇒ this

Extend the default values. (Model.defaults().values)

Kind: instance method of Extension

ParamTypeDescription
valueObject

The value to extend it with.

Model

Kind: global class

model.assign(values) ⇒ undefined

Assign values to the model.

Kind: instance method of Model

ParamTypeDescription
valuesObject

Key-value pairs to be assigned.

Example

let book = await Book.findOne()
// Book { _id: 'XXX', title: '...' }
book.assign({ title: ',,,', one: 1 })
// now book is Book { _id: 'XXX', title: ',,,', one: 1 }

model.getClass() ⇒ function

Get the class in the instance.

Kind: instance method of Model

model.toPOJO() ⇒ Object

Get a plain object representation of the model.

Kind: instance method of Model

model.toJSON() ⇒ string

Get a JSON string representation of the model.

Kind: instance method of Model

model.save() ⇒ Promise.<this>

Save the model to the database.

Kind: instance method of Model
Example

let book = new Book()
book.title = '...'
// now book is Book { title: '...' }
await book.save()
// now book is Book { _id: 'XXX', title: '...'}

model.remove() ⇒ Promise.<number>

Remove the model from the database.

Kind: instance method of Model
Example

let book = await Book.findOne()
await book.remove()
// now book is not persisted in the database

model.duplicate() ⇒ Promise.<static>

Create a duplicate of the model (in database).

Kind: instance method of Model
Returns: Promise.<static> - The duplicate...
Example

let book = await Book.findOne()
// Book { _id: 'XXX', title: '...' }
let duplicate = await book.duplicate()
// Book { _id: 'YYY', title: '...' }

Model.datastore() ⇒ null | string | Object | Datastore

Get the datastore configuration of the model. For more information visit: https://github.com/louischatriot/nedb#creatingloading-a-database

Kind: static method of Model
Returns: null | string | Object | Datastore - The datastore configuration or a nedb-promises datastore instance.
Example

return {
    inMemoryOnly: true,
    timestampData: true
}

Example

const Datastore = require('nedb-promises')
return Datastore.create('filename.db')

Model.defaults() ⇒ Object

Get the defaults of the model.

Note:

The returned object has to contain at least three objects:

  • query - used in Model.find, Model.findOne and Model.count
  • projection - used in Model.find and Model.findOne
  • values - used in Model.insert

It's good practice not to return a completely new value, but to return an extended one based on the parent's defaults.

Kind: static method of Model
Example

return extend(true, super.defaults(), { ... })

Model.find(query, projection) ⇒ Cursor

Find models that match a query. https://github.com/louischatriot/nedb#finding-documents

Note: This is the only method of the Model class that is not an async function. That is because of the way the Cursor works. The cool thing about Cursors is that you can await their results.

Kind: static method of Model
Returns: Cursor - https://github.com/bajankristof/nedb-promises#find-query--projection--

ParamType
queryObject
projectionObject

Example

return await Book.find({ ... }).sort({ ... })

Example

// to get all books
return await Book.find()

Model.findOne(query, projection) ⇒ Promise.<static>

Find one model that matches a query. https://github.com/louischatriot/nedb#finding-documents

Kind: static method of Model

ParamType
queryObject
projectionObject

Model.count(query) ⇒ Promise.<number>

Count models that match a query. https://github.com/louischatriot/nedb#counting-documents

Kind: static method of Model

ParamType
queryObject

Model.insert(values) ⇒ Promise.<(static|Array.<static>)>

Insert a document or bulk insert documents. Returns the inserted documents in model format. https://github.com/louischatriot/nedb#inserting-documents

Kind: static method of Model

ParamType
valuesObject | Array.<Object>

Example

await Book.insert({ title: '...' })
// Book { _id: 'XXX', title: '...' }

Example

await Book.insert([ { title: '...' }, { title: ',,,' } ])
// [ Book { _id: 'XXX', title: '...' }, Book { _id: 'YYY', title: ',,,' } ]

Model.update(query, values, options) ⇒ Promise.<*>

Update models that match a query. https://github.com/louischatriot/nedb#updating-documents By default it returns the number of updated documents.

You can set options.returnUpdatedDocs to true to get the updated documents as models.

Kind: static method of Model

ParamType
queryObject
valuesObject
optionsObject

Example

await Book.update({ ... }, { $set: { ... } })
// 1

Model.remove(query, options) ⇒ Promise.<number>

Remove models that match a query. https://github.com/louischatriot/nedb#removing-documents By default removing multiple documents is enabled. Set options.multi to false to disable it.

Kind: static method of Model

ParamType
queryObject
optionsObject

Example

await Book.remove({ ... })
// 5

Model.create(values) ⇒ Promise.<(static|Array.<static>)>

Create a model and save it to the database. (An alias to insert...)

Kind: static method of Model

ParamType
valuesObject | Array.<Object>

Model.ensureIndex(options) ⇒ Promise.<undefined>

Creates an index for a given field name. https://github.com/louischatriot/nedb#indexing

Kind: static method of Model

ParamType
optionsObject

Model.removeIndex(field) ⇒ Promise.<undefined>

Removes the index for a given field name. https://github.com/louischatriot/nedb#indexing

Kind: static method of Model

ParamType
fieldstring

Model.use(extension) ⇒ boolean

Use an extension on the model.

Kind: static method of Model
Returns: boolean - true if all extensions were applied successfully.

ParamTypeDescription
extensionfunction | Array.<function()>

Extension constructor(s).

Example

Book.use(SoftRemoves)

Model.addListener()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.emit()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.eventNames()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.getMaxListeners()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.listenerCount()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.listeners()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.on()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.once()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.prependListener()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.prependOnceListener()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.removeAllListeners()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.removeListener()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.setMaxListeners()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Model.rawListeners()

Derived from EventEmitter...

https://nodejs.org/api/events.html#events_emitter_emit_eventname_args

https://github.com/bajankristof/nedb-promises/blob/master/docs.md#Datastore

Kind: static method of Model

Encryption

Kind: global class
Summary: Use this extension to encrypt your model's database file.

This extension requires your model class to have a static encryption method that should either return a string (in this case this will be used as the password for the encryption and the algorithm will be aes256) or an object (that must have a password property, also in this case you can specify the encryption algorithm by providing an algorithm property too).

Be aware that if you already have a database that has been created before applying the Encryption extension you might get the below error:

Error: More than 10% of the data file is corrupt, 
the wrong beforeDeserialization hook may be used. 
Cautiously refusing to start NeDB to prevent dataloss.

Example

const { Model, Encryption } = require('nedb-models')

class User extends Model {
    static encryption() {
        return 'password'
    }
}

User.use(Encryption)

Example

const { Model, Encryption } = require('nedb-models')

class User extends Model {
    static encryption() {
        return {
            password: 'password',
            algorithm: 'aes192'
        }
    }
}

User.use(Encryption)

SoftRemoves

Kind: global class
Summary: Use this extension to setup soft removal functionality for your model.

The extension sets up:

  • removedAt property on your inserted models with a default value of null
  • forceRemove async instance method (replaces the original remove method)
  • forceRemove async static method (replaces the original remove method)
  • remove async instance method just updates the removedAt property with the current timestamp
  • remove async static method just updates the removedAt property with the current timestamp
  • find, findOne and count automatically exclude models that have a non null removedAt property
  • findRemoved async static method to query removed models
  • restore async instance method to restore a removed model
  • restore async static method to restore models

Timestamps

Kind: global class
Summary: Use this extension to add createdAt and removedAt timestamps to your models automatically.

This extension sets up:

  • createdAt and updatedAt timestamps on insert
  • updates updatedAt automatically on update

It uses nedb's timestampData option to achieve this. To learn more visit: https://github.com/louischatriot/nedb#creatingloading-a-database

augmenter(defaults) ⇒ function

Kind: global function
Summary: Get a safe object extender from a default object. (Why is it safe? Because it clones both the defaults and the given object, so it doesn't modify them.)

ParamTypeDescription
defaultsObject

The defaults to extend.

Example

augmenter({ one: true })({ two: false })
// { one: true, two: false }

Example

augmenter({ one: true })({ one: false, two: false })
// { one: false, two: false }

converter(__class) ⇒ function

Kind: global function
Summary: Get a converter from a model class.

ParamTypeDescription
__classfunction

The model class.

Example

converter(Book)({ title: '...' })
// Book { title: '...' }

Example

converter(Book)([ { title: '...' }, { title: ',,,' } ])
// [ Book { title: '...' }, Book { title: ',,,' } ]

datastore(__class) ⇒ Proxy.<Datastore>

Kind: global function
Summary: Get a datastore instance from a model class.

ParamTypeDescription
__classfunction

The model class.

Example

datastore(Book)()
// Proxy.<Datastore> based on Book.datastore()

encrypter(algorithm, password) ⇒ function

Kind: global function
Summary: Get a simple encrypt function. (crypto.createCipher)

This helper is used by the Encryption extension.

ParamTypeDescription
algorithmstring

An OpenSSL algorithm (eg.: aes256).

passwordstring

The password to encrypt the data with.

Example

const encrypt = encrypter('aes256', 'password')
encrypt('hello')
// 54f505e1106e9ffc22cd64705c3819d4

decrypter(algorithm, password) ⇒ function

Kind: global function
Summary: Get a simple decrypt function. (crypto.createDecipher)

This helper is used by the Encryption extension.

ParamTypeDescription
algorithmstring

An OpenSSL algorithm (eg.: aes256).

passwordstring

The password to decrypt the data with.

Example

const decrypt = decrypter('aes256', 'password')
decrypt('54f505e1106e9ffc22cd64705c3819d4')
// hello