API Reference

Classes

AbstractBaseModel

Abstract Base Model representation for all created Document instances. Represents just the document data and generic properties and functions. Also used for "object" abstraction / representation of sub documents that are not actual Models / Documents. Clients should never have to call this directly.

BaseModelEventEmitter

BaseModel implements AbstractBaseModel and is a representation for all created Document instances that have a user defined schema. Represents just the document data and generic properties and functions. Clients should never have to call this directly. Inherits EventEmitter

CouchbaseDocumentDocument

CouchbaseDocument inherits Document and handles all the database related actions. Clients should never have to call this directly.

DocumentBaseModel

Base constructor for all created Document instances. Represents just the document data and generic properties and functions. Clients should never have to call this directly.

LoungeBucket

The Lounge module The exports object of the lounge module is an instance of this class. Most apps will only use this one instance. We copy all Couchbase Bucket methods and properties so you can call them generically = require(this instance as well.

ModelCouchbaseDocument

Model class is a base class for all ModelInstances and it extends CouchbaseDocument

ModelInstanceModel

ModelInstance class is the compiled class from a schema definition. It extends Model. All models generated are an instance of ModelInstance. It also inherits grappling-hook See grappling-hook for pre and post hooks.

Schema

Schema class represents the schema definition. It includes properties, methods, static methods, and any middleware we want to define.

AbstractBaseModel

Abstract Base Model representation for all created Document instances. Represents just the document data and generic properties and functions. Also used for "object" abstraction / representation of sub documents that are not actual Models / Documents. Clients should never have to call this directly.

Kind: global class

new AbstractBaseModel(values, options, schema)

Clients do not need to create AbstractBaseModel instances manually.

Param Type Description
values Object the object data
options Object creation options
options.clone Boolean Whether to deep clone the incoming data. Default: false. Make sure you wish to do this as it has performance implications. This is useful if you are creating multiple instances from same base data and then wish to modify each instance.
schema Schema schema instance

abstractBaseModel.schema ⇒ Schema

Get the model schema instance

Kind: instance property of AbstractBaseModel
Access: public

abstractBaseModel.set()

Sets data on the document based on the schema. Accepts a key of property and value for the property, or object representing the data for document.

Kind: instance method of AbstractBaseModel
Access: public
Example

user.set('fistName', 'Joe')
user.set({ lastName: 'Smith' })

abstractBaseModel.get(path) ⇒ *

Gets value at a specified path.

Kind: instance method of AbstractBaseModel
Returns: * - The value at the path.

Param Type Description
path String The path / property to retrieve.

abstractBaseModel.toObject(options) ⇒ Object

Converts this document into a plain javascript object.

Kind: instance method of AbstractBaseModel
Returns: Object - Plain javascript object representation of document.
Access: public

Param Type Description
options Object
options.transform function a transform function to apply to the resulting document before returning.
options.virtuals Boolean apply virtual getters. Default: false
options.minimize Boolean remove empty objects. Default: true
options.serializable Boolean whether to include serializable properties. Default: true
options.dateToISO Boolean convert dates to string in ISO format using Date.toISOString(). Default: true

Example

var userSchema = lounge.schema({ name: String })
var User = lounge.model('User', userSchema)
var user = new User({name: 'Joe Smith'})
console.log(user) // automatically invokes toObject()

Example (Example with transform option.)

var xform = function (doc, ret, options) {
  ret.name = ret.name.toUpperCase()
  return ret
}
console.dir(user.toObject({transform: xform}) // { name: 'JOE SMITH' }

abstractBaseModel.toJSON(options) ⇒ Object

Similar as toObject but applied when JSON.stringify is called

Kind: instance method of AbstractBaseModel
Returns: Object - Plain javascript object representation of document.
Access: public

Param Type Description
options Object Same options as toObject.

abstractBaseModel.inspect()

Helper for console.log. Just invokes default toObject.

Kind: instance method of AbstractBaseModel
Access: public

abstractBaseModel.toString()

Helper for console.log. Alias for inspect.

Kind: instance method of AbstractBaseModel
Access: public

abstractBaseModel.clear()

Clear the document data. This can be overridden at schema level using Schema.set().

Kind: instance method of AbstractBaseModel

abstractBaseModel.getErrors()

Gets the errors object.

Kind: instance method of AbstractBaseModel

abstractBaseModel.clearErrors()

Clears all the errors.

Kind: instance method of AbstractBaseModel

abstractBaseModel.hasErrors() ⇒ Boolean

Checks whether we have any errors.

Kind: instance method of AbstractBaseModel
Returns: Boolean - true if we have errors, false otherwise.

BaseModel ⇐ EventEmitter

BaseModel implements AbstractBaseModel and is a representation for all created Document instances that have a user defined schema. Represents just the document data and generic properties and functions. Clients should never have to call this directly. Inherits EventEmitter

Kind: global class
Extends: EventEmitter

new BaseModel()

Clients do not need to create BaseModel instances manually.

CouchbaseDocument ⇐ Document

CouchbaseDocument inherits Document and handles all the database related actions. Clients should never have to call this directly.

Kind: global class
Extends: Document

new CouchbaseDocument(values, cas, options, schema, name)

Clients do not need to create Document manually.

Param Type Description
values Object the object data
cas Object the Couchbase CAS value for the document
options Object creation options
options.clone Boolean Whether to deep clone the incoming data. Default: false. Make sure you wish to do this as it has performance implications. This is useful if you are creating multiple instances from same base data and then wish to modify each instance.
schema Schema schema instance
name String the model name

couchbaseDocument.cas ⇒ String

Returns the string representation of CAS value.

Kind: instance property of CouchbaseDocument
Example

console.log(doc.cas) // String: 00000000a71626e4

couchbaseDocument.db ⇒ Driver | null

Gets the database driver of the model

Kind: instance property of CouchbaseDocument

couchbaseDocument.config ⇒ Object

Gets the config object

Kind: instance property of CouchbaseDocument

couchbaseDocument.modelName : String

The name the name of the model. This is both a static and instance property.

Kind: instance property of CouchbaseDocument
Example

var schema = lounge.schema({ name: String })
var Cat = lounge.model('Cat', schema)
var kitty = new Cat({ name: 'Zildjian' })
console.log(Cat.modelName) // 'Cat'
console.log(kitty.modelName) // 'Cat'

couchbaseDocument._isNew : Boolean

Has a key been generated for this document.

Kind: instance property of CouchbaseDocument
Example

var schema = lounge.schema({ name: String })
var Cat = lounge.model('Cat', schema)
var kitty = new Cat({ name: 'Zildjian' })
console.log(kitty._isNew) // true
var kat = new Cat({ id: '123abc', name: 'Sabian' })
console.log(kat._isNew) // false

couchbaseDocument.getCAS(raw) ⇒ String | Object

Returns the document CAS value.

Kind: instance method of CouchbaseDocument
Returns: String | Object - the CAS value

Param Type Description
raw Boolean If true returns the raw CAS document. If false returns string representation of CAS. Defaults to false.

Example

console.log(doc.getCAS()) // String: 00000000a71626e4
console.log(doc.getCAS(true)) // Object: CouchbaseCas<11338961768815788032>

couchbaseDocument.save(options, replicate_to, fn)

Save the current model instance. Calls db set function for the model id and saves the properties.

Kind: instance method of CouchbaseDocument

Param Type Description
options Object The save options. All options not present here are first looked up from schema options, and then from config options.
options.storeFullReferenceId Boolean whether to save embedded document property values as full document keys or just the base value
options.storeFullKey Boolean whether to save the internal document key property as fully expanded value or as the simple value
options.refIndexKeyPrefix String lookup index document key prefix.
options.waitForIndex Boolean whether we want to wait for indexing to finish before returning. Default: false.
options.virtuals Boolean whether we want to save virtuals. Default: false.
options.minimize Boolean to "minimize" the document by removing any empty properties. Default: true
options.expiry Number couchbase upsert option
options.persist_to Number couchbase persist_to option
replicate_to Number couchbase option
fn function callback

Example

var user = new User({ name: 'Bob Smith', email: 'bsmith@acme.com' })
user.save(function(err, savedDoc) {
  if(err) console.log(err)
})

couchbaseDocument.index(options, fn)

Update all lookup documents for this document instance. Creates new lookup documents for properties that have changed and deletes the old ones not needed any more.

Kind: instance method of CouchbaseDocument

Param Type Description
options Object
options.storeFullReferenceId Boolean whether we store full document id in reference documents
options.atomicLock Boolean whether to use atomicLock
fn function callback

couchbaseDocument.remove(options, fn)

Removes the instance from the database. Calls the bucket remove() function. Options can be passed to the driver.

Kind: instance method of CouchbaseDocument

Param Type Description
options Object Options to be passed to the Couchbase Bucket.remove() function.
fn function callback

Example

user.remove(function(err, doc) {
  if(err) console.log(err)
})

couchbaseDocument.removeIndexes(options, fn)

Removes all lookup / index documents for this document.

Kind: instance method of CouchbaseDocument

Param Type Description
options Object
options.storeFullReferenceId Boolean whether we store full document id in reference documents
fn function callback

couchbaseDocument.populate(options, fn)

Populates this instance given the options

Kind: instance method of CouchbaseDocument

Param Type Description
options Boolean | String | Array populate options, can be a Boolean; String representing a path; Object with form { path: String, target: String} where path is the path to be populated and target is the target field into which to populate. If this format is used, target should be part of schema; or an Array of Strings or Object.
fn function Callback

Example (Populate an instance)

User.findBy(userId, (err, user) {
  console.log(user.company) // ID
  user.populate((err, populatedUser) => {
    console.log(user.company) // full populated sub documnet
  })
})

Example (Populate a specific path within an instance)

User.findBy(userId, (err, user) {
  console.log(user.company) // ID
  user.populate('company', (err, populatedUser) => {
    console.log(user.company) // full populated sub documnet
  })
})

couchbaseDocument.getDocumentKeyValue(full) ⇒ String

Helper function to get the document key.

Kind: instance method of CouchbaseDocument
Returns: String - document key
Access: public

Param Type Description
full Boolean If true the full expanded value of the key will be returned. If there were any suffix and / or prefix defined in schema they are applied.

Example

var schema = lounge.schema({ email: String }, { keyPrefix: 'user::'})
var User = lounge.model('User', schema)
var user = new User({ email: 'bsmith@acme.com' })
console.log(user.getDocumentKeyValue()) // 114477a8-1901-4146-8c90-0fc9eec57a58
console.log(user.getDocumentKeyValue(true)) // user::114477a8-1901-4146-8c90-0fc9eec57a58

couchbaseDocument.getDocumentKeyKey() ⇒ String

Gets the Document key property name.

Kind: instance method of CouchbaseDocument
Returns: String - Document key property name
Access: public
Example

var schema = lounge.schema({ email: { type: String, key: true, generate: false }})
var User = lounge.model('User', schema)
var user = new User({ email: 'bsmith@acme.com' })
console.log(user.getDocumentKeyKey()) // email

CouchbaseDocument.findById(id, options, fn)

All models created come with a static function findById that can be used to look up a single or multiple keys and retrieve documents from the database. If key does not exist and document is not found we do not return an error but also no model is generated. This is different than present couchbase module behaviour.

Kind: static method of CouchbaseDocument

Param Type Description
id String | Array the document id / key or an array of keys
options Object
options.populate Boolean | String | Array populate options, can be a Boolean; String representing a path; Object with form { path: String, target: String } where path is the path to be populated and target is the target field into which to populate. If this format is used, target should be part of schema; or an Array of Strings or Object.
options.keepSortOrder Boolean If getting an array of objects, whether we should keep same sort order of returned objects as the id's passed in. Default: false
options.missing Boolean If set to false we won't return missing keys as the final param in the callback. This option overwrites the Lounge config missing option. Default: true.
fn function callback

Example

User.findById('user123', function(err, doc, missing) {
  if(err) console.log(err) // there was an error looking up the key
  else if(!doc) console.log('no document found')
  else console.log(doc) // doc is instance of User and will print it out
})

CouchbaseDocument.remove(id, options, fn)

Removes specified document(s).

Kind: static method of CouchbaseDocument

Param Type Description
id String | Array id(s) to remove
options Object options
options.lean Boolean if true we will directly do document removal. We do not create an instance of model. No middleware is invoked. No indexes updated. Embedded documents are not deleted. Default: false.
options.removeRefs Boolean If set to true will remove embedded reference documents. Default: false.
fn function callback

Example

User.remove('user123', function(err, doc) {
  if(err) console.log(err)
})

Document ⇐ BaseModel

Base constructor for all created Document instances. Represents just the document data and generic properties and functions. Clients should never have to call this directly.

Kind: global class
Extends: BaseModel

new Document(values, options, schema, name)

Clients do not need to create Document manually.

Param Type Description
values Object the object data
options Object creation options
options.clone Boolean Whether to deep clone the incoming data. Default: false. Make sure you wish to do this as it has performance implications. This is useful if you are creating multiple instances from same base data and then wish to modify each instance.
schema Schema schema instance
name String the model name

document.modelName : String

The name the name of the model. This is both a static and instance property.

Kind: instance property of Document
Example

var schema = lounge.schema({ name: String })
var Cat = lounge.model('Cat', schema)
var kitty = new Cat({ name: 'Zildjian' })
console.log(Cat.modelName) // 'Cat'
console.log(kitty.modelName) // 'Cat'

document._isNew : Boolean

Has a key been generated for this document.

Kind: instance property of Document
Example

var schema = lounge.schema({ name: String })
var Cat = lounge.model('Cat', schema)
var kitty = new Cat({ name: 'Zildjian' })
console.log(kitty._isNew) // true
var kat = new Cat({ id: '123abc', name: 'Sabian' })
console.log(kat._isNew) // false

document.getDocumentKeyValue(full) ⇒ String

Helper function to get the document key.

Kind: instance method of Document
Returns: String - document key
Access: public

Param Type Description
full Boolean If true the full expanded value of the key will be returned. If there were any suffix and / or prefix defined in schema they are applied.

Example

var schema = lounge.schema({ email: String }, { keyPrefix: 'user::'})
var User = lounge.model('User', schema)
var user = new User({ email: 'bsmith@acme.com' })
console.log(user.getDocumentKeyValue()) // 114477a8-1901-4146-8c90-0fc9eec57a58
console.log(user.getDocumentKeyValue(true)) // user::114477a8-1901-4146-8c90-0fc9eec57a58

document.getDocumentKeyKey() ⇒ String

Gets the Document key property name.

Kind: instance method of Document
Returns: String - Document key property name
Access: public
Example

var schema = lounge.schema({ email: { type: String, key: true, generate: false }})
var User = lounge.model('User', schema)
var user = new User({ email: 'bsmith@acme.com' })
console.log(user.getDocumentKeyKey()) // email

Document.getDocumentKeyKey() ⇒ String

Gets the Document key property name.

Kind: static method of Document
Returns: String - Document key property name
Access: public
Example

var schema = lounge.schema({ email: { type: String, key: true, generate: false }});
var User = lounge.model('User', schema);
console.log(User.getDocumentKeyKey()); // email

Document.getDocumentKeyValue(id, full) ⇒ string

Static version of getDocumentKeyValue.

Kind: static method of Document
Returns: string - Document key / id
Access: public

Param Type Description
id String id of the document
full Boolean If true the full expanded value of the key will be returned. If there were any suffix and / or prefix defined in schema they are applied.

Example

// assuming keyPrefix: 'user::'
console.log(User.getDocumentKeyValue('114477a8-1901-4146-8c90-0fc9eec57a58', true)) // user::114477a8-1901-4146-8c90-0fc9eec57a58
console.log(User.getDocumentKeyValue('user::114477a8-1901-4146-8c90-0fc9eec57a58', true)) // user::114477a8-1901-4146-8c90-0fc9eec57a58
console.log(User.getDocumentKeyValue('user::114477a8-1901-4146-8c90-0fc9eec57a58', false)) // 114477a8-1901-4146-8c90-0fc9eec57a58
console.log(User.getDocumentKeyValue('114477a8-1901-4146-8c90-0fc9eec57a58', false)) // 114477a8-1901-4146-8c90-0fc9eec57a58

Lounge ⇐ Bucket

The Lounge module The exports object of the lounge module is an instance of this class. Most apps will only use this one instance. We copy all Couchbase Bucket methods and properties so you can call them generically = require(this instance as well.

Kind: global class
Extends: Bucket

new Lounge(options)

The Lounge constructor

Param Type Description
options Object
options.keyPrefix String key prefix for all keys. No default. Generally useful if you wish to namespace documents. Example: app::env::.
options.keySuffix String Similar as prefix but used as a suffix
options.storeFullReferenceId Boolean whether to store embedded document keys as fully expanded keys (with prefix and suffix applied) or just the minimized version. default: false
options.storeFullKey Boolean Similarly to store the fully expanded document key inside the key property. default: false
options.alwaysReturnArrays Boolean set to true to force findyById to always return an array of documents even if only a single key is passed in
options.refIndexKeyPrefix String reference lookup index document key prefix. The name of the index is appended. default: $ref_by
options.delimiter String delimiter string used for concatenation in reference document key expansion / generation. default: '_'. This is prepended to the reference document key.
options.waitForIndex Boolean When documents are saved, indexes are updated. We can wait for this operation to finish before returning = require(save(). Default: false
options.minimize Boolean "minimize" schemas by removing empty objects. Default: true
options.missing Boolean By default the findById and index query functions return 3 parameters to the callback: (err, docs, missing). If this option is set to false we won't return missing keys as the final param in the callback. Default: true.
options.retryTemporaryErrors Boolean Whether to automatically backoff/retry on temporary couchbase errors. Default: false. See https://github.com/bojand/couchbase-driver
options.tempRetryTimes Number The number of attempts to make when backing off temporary errors. See async.retry. Default: 5. See https://github.com/bojand/couchbase-driver
options.tempRetryInterval Number The time to wait between retries, in milliseconds, when backing off temporary errors . See async.retry. Default: 50. See https://github.com/bojand/couchbase-driver
options.atomicRetryTimes Number The number of attempts to make within Driver.atomic(). Default: 5. See https://github.com/bojand/couchbase-driver
options.atomicRetryInterval Number The time to wait between retries, in milliseconds, within Driver.atomic(). Default: 0. See https://github.com/bojand/couchbase-driver
options.atomicLock Boolean Whether to use getAndLock or standard get during atomic operations within indexing. Default: true. See https://github.com/bojand/couchbase-driver
options.promisify Boolean to enable promise support. By default all async functions support promises and return a promise. To disable promise support set this option to false, ideally at start before doing connect or any other operations. Default: true.
options.errorOnMissingIndex Boolean error when a document referenced by index reference document is missing. Default: false The error will have reference property of document reference target document id(s). The error will have missing property of missing document ids.
options.emitErrors Boolean Whether to broadcast error events. Default: true

lounge.Schema

The Lounge Schema constructor

Kind: instance property of Lounge

lounge.Model

The Lounge Model constructor.

Kind: instance property of Lounge

lounge.CouchbaseDocument

The Lounge CouchbaseDocument constructor.

Kind: instance property of Lounge

lounge.Document

The Lounge Document constructor.

Kind: instance property of Lounge

lounge.Lounge

The Lounge constructor The exports of the Lounge module is an instance of this class.

Kind: instance property of Lounge

lounge.connect(options, fn) ⇒ Bucket

Connect to the database. You may define Models before connecting, but you should not create any actual document instances before connecting to the database.

Kind: instance method of Lounge
Returns: Bucket - Couchbase Bucket instance
Access: public

Param Type Description
options Object
options.connectionString String connection string for the cluster
options.bucket String | Bucket name of the bucket or the actual Couchbase bucket instance
options.username String username
options.password String password
options.certpath String certpath for cluster
options.mock Boolean whether to use mocking
fn function callback

Example

lounge.connect({
  connectionString: 'couchbase://127.0.0.1',
  bucket: 'lounge_test'
})

lounge.disconnect()

Disconnect = require(the bucket. Deletes all defined models.

Kind: instance method of Lounge

lounge.schema(descriptor, options) ⇒ Schema

Creates a schema. Prefer to use this over Schema constructor as this will pass along Lounge config settings.

Kind: instance method of Lounge
Returns: Schema - created Schema instance
Access: public

Param Type Description
descriptor Object the schema descriptor
options Object Schema options

Example

var schema = lounge.schema({ name: String })

lounge.model(name, schema, options) ⇒ ModelInstance

Creates a model = require(a schema.

Kind: instance method of Lounge
Returns: ModelInstance - The created ModelInstance class.
Access: public

Param Type Description
name String name of the model.
schema Schema instance
options Object
options.freeze Object to Freeze model. See Object.freeze. Default: true

Example

var Cat = lounge.model('Cat', schema)

lounge.getModel(name) ⇒ Model | undefined

Returns the model given the name.

Kind: instance method of Lounge
Returns: Model | undefined - The ModelInstance or undefined if the model by that name does not exist.

Param
name

Example

var Cat = lounge.getModel('Cat')

lounge.setOption(key, value)

Sets lounge config options

Kind: instance method of Lounge
Access: public

Param Type Description
key String the config key
value * option value

lounge.getOption(key) ⇒ *

Get config option.

Kind: instance method of Lounge
Returns: * - Option value

Param Type Description
key String the config key

lounge.modelNames() ⇒ Array

Returns an array of model names created on this instance of Lounge.

Kind: instance method of Lounge
Returns: Array - Array of model names registered.
Access: public
Example

console.log(lounge.modelNames()) // [ 'Cat', 'Dog' ]

Model ⇐ CouchbaseDocument

Model class is a base class for all ModelInstances and it extends CouchbaseDocument

Kind: global class
Extends: CouchbaseDocument

new Model()

Model class is a base class for all ModelInstances and it extends CouchbaseDocument

model.cas ⇒ String

Returns the string representation of CAS value.

Kind: instance property of Model
Example

console.log(doc.cas) // String: 00000000a71626e4

model.db ⇒ Driver | null

Gets the database driver of the model

Kind: instance property of Model

model.config ⇒ Object

Gets the config object

Kind: instance property of Model

model.modelName : String

The name the name of the model. This is both a static and instance property.

Kind: instance property of Model
Example

var schema = lounge.schema({ name: String })
var Cat = lounge.model('Cat', schema)
var kitty = new Cat({ name: 'Zildjian' })
console.log(Cat.modelName) // 'Cat'
console.log(kitty.modelName) // 'Cat'

model._isNew : Boolean

Has a key been generated for this document.

Kind: instance property of Model
Example

var schema = lounge.schema({ name: String })
var Cat = lounge.model('Cat', schema)
var kitty = new Cat({ name: 'Zildjian' })
console.log(kitty._isNew) // true
var kat = new Cat({ id: '123abc', name: 'Sabian' })
console.log(kat._isNew) // false

model.getCAS(raw) ⇒ String | Object

Returns the document CAS value.

Kind: instance method of Model
Returns: String | Object - the CAS value

Param Type Description
raw Boolean If true returns the raw CAS document. If false returns string representation of CAS. Defaults to false.

Example

console.log(doc.getCAS()) // String: 00000000a71626e4
console.log(doc.getCAS(true)) // Object: CouchbaseCas<11338961768815788032>

model.save(options, replicate_to, fn)

Save the current model instance. Calls db set function for the model id and saves the properties.

Kind: instance method of Model

Param Type Description
options Object The save options. All options not present here are first looked up from schema options, and then from config options.
options.storeFullReferenceId Boolean whether to save embedded document property values as full document keys or just the base value
options.storeFullKey Boolean whether to save the internal document key property as fully expanded value or as the simple value
options.refIndexKeyPrefix String lookup index document key prefix.
options.waitForIndex Boolean whether we want to wait for indexing to finish before returning. Default: false.
options.virtuals Boolean whether we want to save virtuals. Default: false.
options.minimize Boolean to "minimize" the document by removing any empty properties. Default: true
options.expiry Number couchbase upsert option
options.persist_to Number couchbase persist_to option
replicate_to Number couchbase option
fn function callback

Example

var user = new User({ name: 'Bob Smith', email: 'bsmith@acme.com' })
user.save(function(err, savedDoc) {
  if(err) console.log(err)
})

model.index(options, fn)

Update all lookup documents for this document instance. Creates new lookup documents for properties that have changed and deletes the old ones not needed any more.

Kind: instance method of Model

Param Type Description
options Object
options.storeFullReferenceId Boolean whether we store full document id in reference documents
options.atomicLock Boolean whether to use atomicLock
fn function callback

model.remove(options, fn)

Removes the instance from the database. Calls the bucket remove() function. Options can be passed to the driver.

Kind: instance method of Model

Param Type Description
options Object Options to be passed to the Couchbase Bucket.remove() function.
fn function callback

Example

user.remove(function(err, doc) {
  if(err) console.log(err)
})

model.removeIndexes(options, fn)

Removes all lookup / index documents for this document.

Kind: instance method of Model

Param Type Description
options Object
options.storeFullReferenceId Boolean whether we store full document id in reference documents
fn function callback

model.populate(options, fn)

Populates this instance given the options

Kind: instance method of Model

Param Type Description
options Boolean | String | Array populate options, can be a Boolean; String representing a path; Object with form { path: String, target: String} where path is the path to be populated and target is the target field into which to populate. If this format is used, target should be part of schema; or an Array of Strings or Object.
fn function Callback

Example (Populate an instance)

User.findBy(userId, (err, user) {
  console.log(user.company) // ID
  user.populate((err, populatedUser) => {
    console.log(user.company) // full populated sub documnet
  })
})

Example (Populate a specific path within an instance)

User.findBy(userId, (err, user) {
  console.log(user.company) // ID
  user.populate('company', (err, populatedUser) => {
    console.log(user.company) // full populated sub documnet
  })
})

model.getDocumentKeyValue(full) ⇒ String

Helper function to get the document key.

Kind: instance method of Model
Returns: String - document key
Access: public

Param Type Description
full Boolean If true the full expanded value of the key will be returned. If there were any suffix and / or prefix defined in schema they are applied.

Example

var schema = lounge.schema({ email: String }, { keyPrefix: 'user::'})
var User = lounge.model('User', schema)
var user = new User({ email: 'bsmith@acme.com' })
console.log(user.getDocumentKeyValue()) // 114477a8-1901-4146-8c90-0fc9eec57a58
console.log(user.getDocumentKeyValue(true)) // user::114477a8-1901-4146-8c90-0fc9eec57a58

model.getDocumentKeyKey() ⇒ String

Gets the Document key property name.

Kind: instance method of Model
Returns: String - Document key property name
Access: public
Example

var schema = lounge.schema({ email: { type: String, key: true, generate: false }})
var User = lounge.model('User', schema)
var user = new User({ email: 'bsmith@acme.com' })
console.log(user.getDocumentKeyKey()) // email

ModelInstance ⇐ Model

ModelInstance class is the compiled class from a schema definition. It extends Model. All models generated are an instance of ModelInstance. It also inherits grappling-hook See grappling-hook for pre and post hooks.

Kind: global class
Extends: Model

new ModelInstance(data, options, cas)

This would be the constructor for the generated models.

Param Type Description
data Object the model instance data
options Object optional creation options
options.clone Boolean Whether to deep clone the incoming data. Default: false. Make sure you wish to do this as it has performance implications. This is useful if you are creating multiple instances from same base data and then wish to modify each instance.
cas Object the Couchbase CAS value

modelInstance.cas ⇒ String

Returns the string representation of CAS value.

Kind: instance property of ModelInstance
Overrides: cas
Example

console.log(doc.cas) // String: 00000000a71626e4

modelInstance.db ⇒ Driver | null

Gets the database driver of the model

Kind: instance property of ModelInstance
Overrides: db

modelInstance.config ⇒ Object

Gets the config object

Kind: instance property of ModelInstance
Overrides: config

modelInstance.modelName : String

The name the name of the model. This is both a static and instance property.

Kind: instance property of ModelInstance
Overrides: modelName
Example

var schema = lounge.schema({ name: String })
var Cat = lounge.model('Cat', schema)
var kitty = new Cat({ name: 'Zildjian' })
console.log(Cat.modelName) // 'Cat'
console.log(kitty.modelName) // 'Cat'

modelInstance._isNew : Boolean

Has a key been generated for this document.

Kind: instance property of ModelInstance
Overrides: _isNew
Example

var schema = lounge.schema({ name: String })
var Cat = lounge.model('Cat', schema)
var kitty = new Cat({ name: 'Zildjian' })
console.log(kitty._isNew) // true
var kat = new Cat({ id: '123abc', name: 'Sabian' })
console.log(kat._isNew) // false

modelInstance.getCAS(raw) ⇒ String | Object

Returns the document CAS value.

Kind: instance method of ModelInstance
Overrides: getCAS
Returns: String | Object - the CAS value

Param Type Description
raw Boolean If true returns the raw CAS document. If false returns string representation of CAS. Defaults to false.

Example

console.log(doc.getCAS()) // String: 00000000a71626e4
console.log(doc.getCAS(true)) // Object: CouchbaseCas<11338961768815788032>

modelInstance.save(options, replicate_to, fn)

Save the current model instance. Calls db set function for the model id and saves the properties.

Kind: instance method of ModelInstance
Overrides: save

Param Type Description
options Object The save options. All options not present here are first looked up from schema options, and then from config options.
options.storeFullReferenceId Boolean whether to save embedded document property values as full document keys or just the base value
options.storeFullKey Boolean whether to save the internal document key property as fully expanded value or as the simple value
options.refIndexKeyPrefix String lookup index document key prefix.
options.waitForIndex Boolean whether we want to wait for indexing to finish before returning. Default: false.
options.virtuals Boolean whether we want to save virtuals. Default: false.
options.minimize Boolean to "minimize" the document by removing any empty properties. Default: true
options.expiry Number couchbase upsert option
options.persist_to Number couchbase persist_to option
replicate_to Number couchbase option
fn function callback

Example

var user = new User({ name: 'Bob Smith', email: 'bsmith@acme.com' })
user.save(function(err, savedDoc) {
  if(err) console.log(err)
})

modelInstance.index(options, fn)

Update all lookup documents for this document instance. Creates new lookup documents for properties that have changed and deletes the old ones not needed any more.

Kind: instance method of ModelInstance
Overrides: index

Param Type Description
options Object
options.storeFullReferenceId Boolean whether we store full document id in reference documents
options.atomicLock Boolean whether to use atomicLock
fn function callback

modelInstance.remove(options, fn)

Removes the instance from the database. Calls the bucket remove() function. Options can be passed to the driver.

Kind: instance method of ModelInstance
Overrides: remove

Param Type Description
options Object Options to be passed to the Couchbase Bucket.remove() function.
fn function callback

Example

user.remove(function(err, doc) {
  if(err) console.log(err)
})

modelInstance.removeIndexes(options, fn)

Removes all lookup / index documents for this document.

Kind: instance method of ModelInstance
Overrides: removeIndexes

Param Type Description
options Object
options.storeFullReferenceId Boolean whether we store full document id in reference documents
fn function callback

modelInstance.populate(options, fn)

Populates this instance given the options

Kind: instance method of ModelInstance
Overrides: populate

Param Type Description
options Boolean | String | Array populate options, can be a Boolean; String representing a path; Object with form { path: String, target: String} where path is the path to be populated and target is the target field into which to populate. If this format is used, target should be part of schema; or an Array of Strings or Object.
fn function Callback

Example (Populate an instance)

User.findBy(userId, (err, user) {
  console.log(user.company) // ID
  user.populate((err, populatedUser) => {
    console.log(user.company) // full populated sub documnet
  })
})

Example (Populate a specific path within an instance)

User.findBy(userId, (err, user) {
  console.log(user.company) // ID
  user.populate('company', (err, populatedUser) => {
    console.log(user.company) // full populated sub documnet
  })
})

modelInstance.getDocumentKeyValue(full) ⇒ String

Helper function to get the document key.

Kind: instance method of ModelInstance
Overrides: getDocumentKeyValue
Returns: String - document key
Access: public

Param Type Description
full Boolean If true the full expanded value of the key will be returned. If there were any suffix and / or prefix defined in schema they are applied.

Example

var schema = lounge.schema({ email: String }, { keyPrefix: 'user::'})
var User = lounge.model('User', schema)
var user = new User({ email: 'bsmith@acme.com' })
console.log(user.getDocumentKeyValue()) // 114477a8-1901-4146-8c90-0fc9eec57a58
console.log(user.getDocumentKeyValue(true)) // user::114477a8-1901-4146-8c90-0fc9eec57a58

modelInstance.getDocumentKeyKey() ⇒ String

Gets the Document key property name.

Kind: instance method of ModelInstance
Overrides: getDocumentKeyKey
Returns: String - Document key property name
Access: public
Example

var schema = lounge.schema({ email: { type: String, key: true, generate: false }})
var User = lounge.model('User', schema)
var user = new User({ email: 'bsmith@acme.com' })
console.log(user.getDocumentKeyKey()) // email

ModelInstance.schema

Schema the schema of this model.

Kind: static property of ModelInstance

ModelInstance.modelName

The name of the model.

Kind: static property of ModelInstance

ModelInstance.lounge

The static lounge instance in the model

Kind: static property of ModelInstance

ModelInstance.config

The config.

Kind: static property of ModelInstance

ModelInstance.db

The driver.

Kind: static property of ModelInstance

Schema

Schema class represents the schema definition. It includes properties, methods, static methods, and any middleware we want to define.

Kind: global class
Access: public

new Schema(descriptor, options)

Creates an object schema

Param Type Description
descriptor Object the schema definition
options Object
options.strict Boolean By default (true), allow only values in the schema to be set. When this is false, setting new fields will dynamically add the field to the schema as type "any".
options.dotNotation Boolean Allow fields to be set via dot notation. Default: true. obj['user.name'] = 'Joe'; -> obj: { user: 'Joe' }
options.minimize Boolean "minimize" schemas by removing empty objects. Default: true
options.toObject Object toObject method.
options.toObject.minimize Boolean "minimize" schemas by removing empty objects. Default: true
options.toObject.transform function transform function
options.toObject.virtuals Boolean whether to include virtual properties. Default: false
options.toObject.dateToISO Boolean convert dates to string in ISO format using Date.toISOString(). Default: false
options.toJSON Object options for toJSON method options, similar to above
options.strict Boolean ensures that value passed in to assigned that were not specified in our schema do not get saved
options.onBeforeValueSet function function called when write operations on an object takes place. Currently, it will only notify of write operations on the object itself and will not notify you when child objects are written to. If you return false or throw an error within the onBeforeValueSet handler, the write operation will be cancelled. Throwing an error will add the error to the error stack.
options.onValueSet function Similar to onBeforeValueSet, but called after we've set a value on the key,
options.saveOptions Object options for couchbase save method, such as expiry, replicate_to, and persist_to. These options will propagate to all save() calls automatically and all index reference documents. If a save() call has those options they are used over ones defined in the schema options.

Example

var schema = new lounge.Schema({ name: String })

Example (with <code>onBeforeValueSet</code>)

var User = lounge.schema({ name: String }, {
  onBeforeValueSet: function(key, value) {
    if(key === 'name' && value.indexOf('Joe') >= 0) {
      return false
    })
  }
})

var User = lounge.model('User', schema)
var user = new User()
user.name = 'Bill' // name not set
user.name = 'Joe Smith' //  { name: 'Joe Smith' }

schema.index(prop, options)

Creates an index on the specified property.

Kind: instance method of Schema
Access: public

Param Type Description
prop String property to create the index on. If an array or property keys, generates compound key based on the property values, order matters.
options Object index options
options.indexName String the index name to be used for lookup function name generation. - by default generated = require(property name.
options.indexType String the index type. 'singe' or 'array'. - default: 'single'
options.refKeyCase String the casing for the reference document key. The default is to take value of the property as is, unmodified, to generate the reference document key. Use this to force reference document key casing. This will also allow you to to query via index function in case insensitive way. options: 'upper' or 'lower'

Example (Simple reference document)

var userSchema = lounge.schema({
  firstName: String,
  lastName: String,
  username: String
})

userSchema.index('username', { indexName: 'UserName' })
var User = lounge.model('User', userSchema)
// use User.findByUserName(username) to query

Example (Simple coumpund document)

var userSchema = lounge.schema({
  email: String,
  username: String
})

userSchema.index(['email', 'username'], { indexName: 'EmailAndUserName' })
var User = lounge.model('User', userSchema)
// use User.findByEmailAndUserName(email, username) to query

schema.method(name, func)

Creates a instance method for the created model. An object of function names and functions can also be passed in.

Kind: instance method of Schema
Access: public

Param Type Description
name String the name of the method
func function the actual function implementation

Example

var userSchema = lounge.schema({
  firstName: String,
  lastName: String
})

userSchema.method('getFullName', function () {
  return this.firstName + ' ' + this.lastName
})

var User = lounge.model('User', userSchema)
var user = new User({
  firstName: 'Joe',
  lastName: 'Smith'
})

console.log(user.getFullName()) // Joe Smith

schema.static(name, val)

Creates a static function or property for the created model. An object of function or property names and functions or values can also be passed in.

Kind: instance method of Schema
Access: public

Param Type Description
name String name of the static property
val * the actual value or static function

Example (Create a static function)

var userSchema = lounge.schema({ name: String })
userSchema.static('foo', function () {
  return 'bar'
})

var User = lounge.model('User', userSchema)
console.log(User.foo()) // 'bar'

Example (Create a static property)

var userSchema = lounge.schema({ name: String })
userSchema.static('FOO', 'bar')
var User = lounge.model('User', userSchema)
console.log(User.FOO) // 'bar'

schema.virtual(name, type, options)

Creates a virtual property for the created model with the given object specifying the get and optionally set function

Kind: instance method of Schema
Access: public

Param Type Description
name String name of the virtual property
type String | function | Object optional type to be used for the virtual property. If not provided default is 'any' type.
options Object virtual options
options.get function the virtual getter function
options.set function the virtual setter function. If not provided the virtual becomes read-only.

Example

var userSchema = lounge.schema({firstName: String, lastName: String})

userSchema.virtual('fullName', String, {
  get: function () {
    return this.firstName + ' ' + this.lastName
  },
  set: function (v) {
    if (v !== undefined) {
      var parts = v.split(' ')
      this.firstName = parts[0]
      this.lastName = parts[1]
    }
  }
})

var User = lounge.model('User', userSchema)

var user = new User({firstName: 'Joe', lastName: 'Smith'})
console.log(user.fullName) // Joe Smith
user.fullName = 'Bill Jones'
console.log(user.firstName) // Bill
console.log(user.lastName) // Jones
console.log(user.fullName) // Bill Jones

schema.set(key, [value])

Sets/gets a schema option.

Kind: instance method of Schema
Access: public

Param Type Description
key String option name
[value] Object if not passed, the current option value is returned

schema.get(key) ⇒ *

Gets a schema option.

Kind: instance method of Schema
Returns: * - the option value
Access: public

Param Type Description
key String option name

schema.pre()

Defines a pre hook for the schema. See grappling-hook.

Kind: instance method of Schema

schema.post()

Defines a post hook for the schema. See grappling-hook.

Kind: instance method of Schema

schema.add(key, descriptor)

Adds the descriptor to the schema at the given key. Or add an object as a descriptor.

Kind: instance method of Schema

Param Type Description
key String | Object the property key
descriptor Object the property descriptor

Example

var userSchema = lounge.schema({firstName: String })
userSchema.add('lastName', String)
userSchema.add({ email: String })

schema.extend(other)

Extends other schema. Copies descriptor properties, methods, statics, virtuals and middleware. If this schema has a named property already, the property is not copied.

Kind: instance method of Schema

Param Type Description
other Schema the schema to extend.

schema.getDocumentKeyValue(id, full) ⇒ String

Helper function to get the document key

Kind: instance method of Schema

Param Type Description
id String the id
full Boolean If true the full expanded value of the key will be returned if there were any suffix and / or prefix defined in schema they are also applied. We test if the passed in id already satisfies expansion.

Example

var schema = lounge.schema({ email: String }, {keyPrefix: 'user::' })
console.log(schema.getDocumentKeyValue('114477a8-1901-4146-8c90-0fc9eec57a58', true)) // user::114477a8-1901-4146-8c90-0fc9eec57a58
console.log(schema.getDocumentKeyValue('user::114477a8-1901-4146-8c90-0fc9eec57a58', true)) // user::114477a8-1901-4146-8c90-0fc9eec57a58
console.log(schema.getDocumentKeyValue('user::114477a8-1901-4146-8c90-0fc9eec57a58', false)) // 114477a8-1901-4146-8c90-0fc9eec57a58
console.log(schema.getDocumentKeyValue('114477a8-1901-4146-8c90-0fc9eec57a58', false)) // 114477a8-1901-4146-8c90-0fc9eec57a58

schema.getRefKey(name, v) ⇒ string

Gets the reference document key value

Kind: instance method of Schema

Param Type Description
name String index name
v String index value

schema.hasRefPath(path) ⇒ boolean

Returns whether this schema has the specified reference path

Kind: instance method of Schema

Param Type Description
path String path to check