Documentation

Thinky

Thinky.init( options ) »

options is an object that can have the following fields:

Note: Passing a boolean for enforce will set all three fields of enforce to this value.

Thinky.getOptions() »

Returns all the options previously set.

Thinky.getOption( optionName ) »

Returns the value for optionName. Possible values:

Thinky.setOptions( options ) »

Overwrite the options defined in options.

The argument options is an object that can have the following fields

Note: Passing a boolean for enforce will set all three fields of enforce to this value.

Note: Setting a value to null will set it to the default value.

Note: Changing the host/port/poolMax/poolMin will create a new pool (the previous one will be drained).
The current behavior when changing poolMin/poolMax will be fixed at some point.

Thinky.disconnect() »

Close all the connections.

Thinky.createModel( name, schema, options ) »

Create a new model

Note about Date: You can pass a native Date object in a Date field or a raw ReQL date object:

{
    $reql_type$: 'TIME',
    epoch_time: <time>, // In seconds -- don't forget to divide by 1000 if you use Date.now()
    timezone: <timezone> // like '+00:00'
}

The returned type is defined by the timeFormat option set in the thinky module. The local timezone is not saved if you use native objects for the moment.

When an object with the field _type is passed, the enforce field will be use to overwrite the global settings for enforcing the schema

Examples of fields for a schema:

{
    stringField: String,
    numberField: Number,
    booleanField: Boolean,
    arrayOfStrings: [String],
    arrayOfNumber: [Number],
    objectField: {
        nestedString: String,
        nestedBoolean: Boolean
    },
    stringFieldWithOptions: {
        _type: String,
        enforce: { missing: false, type: true },
        default: "Constant string as a default" 
    },
    numberFieldWithOptions: {
        _type: Number,
        enforce: { missing: true, type: true } },
        default: function(doc) { return doc["age"] },
    booleanFieldWithOptions: {
        _type: Boolean,
        enforce: { missing: false, type: false }
    },
    objectFieldWithOptions: {
        _type: Object,
        schema: {
            nestedStringField: String,
            nestedNumberField: Number
        },
        enforce: {
            missing: true,
            type: true
        }
    }
    arrayFieldWithOptions: {
        _type: Array,
        schema: [Number],
        enforce: {
            missing: false,
            type: true
        }
    }
}

Note: the fields enforce and default are optional.

Note: the value of enforce is defined by the most local one.

Note: you currently cannot have a field named _type in your model.
This limitation will be removed at some point (by letting the user named the field _type with any available key).

Note: The settings to set a minimum/maximum of elements in an array is on the roadmap.

Model

Model.define( key, method, force=false ) »

Defines a method on the model with the name key. This method can be called by any instances of the model, whether the instances were created before or after the definition of the method.

Note: If a method already exists with such name (including internal methods), an error will be thrown. If you are sure about what you are doing, you can pass the value true for the force argument.

Note: The methods are bound to the prototype of the object. So if the instance of your model has a field hello, you will be able to create a method named hello, but you will not be able to access it with object.hello(). You will have to use object.__proto__.hello()

Model.execute( query, callback ) »

Executes the query and call the callback with two arguments

This method lets you execute arbitrary queries as long as they return objects from the table.

Model.setSchema( schema ) »

Change the schema of a model.

Note: When you change the schema, the instances previously created do not change! And the next updates of the instances will use the new schema (so errors may be thrown).

Conclusion: While available, you probably do not want to use this method.

Model.getSettings() »

Returns the settings of the model.

Model.getPrimaryKey() »

Returns the primary key of the model.

Model.get( id, callback ) »

Retrieves a document (or documents) by primary keys. Returns the query. The query is not executed if callback is not passed.

Note: Thinky does not currently keep track of the created objects (to avoid leaks), so new objects are going to be created even if they somehow already exist.

Model.getAll( value, options, callback ) »

Retrieves documents with a secondary index. Returns the query. The query is not executed if callback is not passed.

Note: If you are using a compound index, you must wrap your values in an array.

Model.pluck( field[s], options, callback ) »

Pluck the field[s] provided. Returns the query. The query is not executed if callback is not passed.

Model.without( field[s], options, callback ) »

Remove the field[s] provided. Returns the query. The query is not executed if callback is not passed.

Model.filter( filterFunction, callback ) »

Retrieve documents based on the filterFunction. Returns the query. The query is not executed if callback is not passed.

Model.skip( skipValue, callback ) »

Retrieve documents of the model and skip skipValue documents. Returns the query. The query is not executed if callback is not passed.

Model.limit( limitValue, callback ) »

Retrieve documents and limit to limitValue documents. Returns the query. The query is not executed if callback is not passed.

Model.orderBy( field, callback ) »

Order results by field. field can be a single field or an array of fields. Fields that start with a - will be ordered in a descending way.

Returns the query. The query is not executed if callback is not passed.

Model.delete( callback ) »

Returns the query. The query is not executed if callback is not passed.

Model.update( update, callback ) »

Returns the query. The query is not executed if callback is not passed.

Model.getJoin( callback ) »

Order results by field. field can be a single field or an array of fields.

Returns the query. The query is not executed if callback is not passed.

Model.count() »

Returns the number of elements in the table of your model. Returns the query. The query is not executed if callback is not passed.

Model.run( callback ) »

Retrieves all the documents.

callback is the callback that is going to be called. Two arguments are passed to the callback:

Model.addListener( event, listener ) »

Add a listener on the model.
Everytime a new instance will be created, the listeners defined on the model will be added to the document.

Note: Previously created document will not have such listeners.

Model.on( event, listener ) »

Alias for addListener

Model.once( event, listener ) »

Add a listener on the model. Everytime a new instance will be created, the listeners defined on the model will be added to the document.

Such listener can be triggered at most once per document.

Model.off( event, listener ) »

Remove the listener bound to the event.

Other ways to use it:

Model.listeners( event, raw ) »

Returns all the listeners for this event. These listeners can be

If event is null or undefined, the object containing all the listeners will be returned.

{
    once: true,
    listener: listener
}

If raw is set to false (default is true), the objects are replaced by the listener they contain.

Model.hasOne( model, fieldName, joinClause ) »

Create a "has one" relation between two models. The arguments are

Example

// Create the models
var Cat = thinky.createModel('Cat', {name: String, idHuman: String}); 
var Human = thinky.createModel('Human', {name: String}); 

// Specify the join
Cat.hasOne(Human, 'owner', {leftKey: 'idHuman', rightKey: 'id'})

// Create a new joined document
kitty = new Cat({name: 'Kitty'});
michel = new Human({name: Michel});
kitty.owner = michel;

kitty.save(function(err, result) {
    if (err) throw err;
    console.log(result); // Note: kitty === result
    /* will print:
    {
        id: "0e4a6f6f-cc0c-4aa5-951a-fcfc480dd05a",
        name: "Catou",
        idHuman: "3851d8b4-5358-43f2-ba23-f4d481358901",
        owner: {
            id: "3851d8b4-5358-43f2-ba23-f4d481358901",
            name: Michel
        }
    }
    */
}, {saveJoin: true});


// Retrieve a document with its joined ones
Cat.get('0e4a6f6f-cc0c-4aa5-951a-fcfc480dd05a', function(err, result) {
    if (err) throw err;
    console.log(result);
    /*  will print
    {
        id: "0e4a6f6f-cc0c-4aa5-951a-fcfc480dd05a",
        name: "Catou",
        idHuman: "3851d8b4-5358-43f2-ba23-f4d481358901",
        owner: {
            id: "3851d8b4-5358-43f2-ba23-f4d481358901",
            name: Michel
        }
    }
    */

}, {getJoin: true})

Model.hasMany( model, fieldName, joinClause, options ) »

Create a "has one" relation between two models. The arguments are

Example:

Cat = thinky.createModel('Cat', {id: String, name: String});
Task = thinky.createModel('Task', {id: String, task: String, catId: String});
Cat.hasMany(Task, 'tasks', {leftKey: 'id', rightKey: 'catId'});

cat = new Cat({name: "Catou"});
task1 = new Task({task: "Catch the red dot"});
task2 = new Task({task: "Eat"});
task3 = new Task({task: "Sleep"});

cat.tasks = [task1, task2, task3];
cat.save({saveJoin: true}, function(err, result) {
    if (err) throw err;

    // Note: cat === result
    console.log(result);
    /* will print
    {
        id: 'b7588193-7fb7-42da-8ee3-897392df3738',
        name: 'Catou',
        tasks: [
            {
                id: 'd4333984-f7c6-48cb-a64e-8d9666d9eaf0',
                task: 'Catch the red dot',
                catId: 'b7588193-7fb7-42da-8ee3-897392df3738'
            },
            {
                id: '09b2eba9-0d26-4e6c-b735-da2442e1caa6',
                task: 'Eat',
                catId: 'b7588193-7fb7-42da-8ee3-897392df3738'
            },
            {
                id: '5cc7eb9e-f924-4cae-89b5-95db19753b0b',
                task: 'Sleep',
                catId: 'b7588193-7fb7-42da-8ee3-897392df3738'
            }
        ]
    }
    */
})

// Retrieve joined documents
Cat.get( 'b7588193-7fb7-42da-8ee3-897392df3738').getJoin( function(err, result) {
    if (err) throw err;
    console.log(result);
    /* will print
    {
        id: 'b7588193-7fb7-42da-8ee3-897392df3738',
        name: 'Catou',
        tasks: [
            {
                id: 'd4333984-f7c6-48cb-a64e-8d9666d9eaf0',
                task: 'Catch the red dot',
                catId: 'b7588193-7fb7-42da-8ee3-897392df3738'
            },
            {
                id: '09b2eba9-0d26-4e6c-b735-da2442e1caa6',
                task: 'Eat',
                catId: 'b7588193-7fb7-42da-8ee3-897392df3738'
            },
            {
                id: '5cc7eb9e-f924-4cae-89b5-95db19753b0b',
                task: 'Sleep',
                catId: 'b7588193-7fb7-42da-8ee3-897392df3738'
            }
        ]
    }
    */
})

Query

Note: These methods are the same as the one defined on Model. The Query function is defined so you can chain methods (like with the driver).

Query.get( id, callback ) »

Query.getAll( value, options, callback ) »

Query.pluck( field[s], options, callback ) »

Query.without( field[s], options, callback ) »

Query.filter(_ filterFunction, callback ) »

Query.delete(_ callback ) »

Query.update(_ update, callback ) »

Model.skip( skipValue, callback ) »

Model.limit( limitValue, callback ) »

Query.orderBy( field, callback ) »

Query.get( id, callback ) »

Query.count() »

Query.getJoin( callback ) »

Document

Document.getModel( ) »

Returns the model of the document.

Document.getSettings( ) »

Returns the settings of the document.

Document.definePrivate( name, method ) »

Defines a method accessible through the key name.

The method will be accessible only by the document iself and not any other documents (including those in the same class).

Document.save( callback ) » Document.save( options, callback ) »

Save the object in the database. Thinky will call insert or update depending on how the object was created.

The event save is triggered if the document is successfully saved.

The argument options can have the following fields:

Document.update( callback ) »

Update the object in the database that has the same primary key.

Document.delete( callback ) » Document.delete( options, callback ) »

Delete the object in the database.

The event delete is triggered if the document is successfully deleted.

The argument options can have the following fields:

Document.merge( newDoc, replace ) »

Merges the fields of newDoc in the document. The merge is recursive.

If replace is set to true, the document will be replaced (that is how you can delete fields).

The event 'change' is triggered if the document is changed.

Note: The new document is checked agains the schema of the model, so the merge may throw an error.

Document.addListener( event, listener ) »

Add a listener for an event.
This method is copied from events.EventEmitter.

Document.on( event, listener ) »

Add a listener for an event.
This method is an alias for Document.addListener.

Document.once( event, listener ) »

Add a listener for an event that is going to be removed once it is triggered once.
Method from events.EventEmitter.

Document.removeListener( event, listener ) »

Remove a listener for an event.
Method from events.EventEmitter.

Document.off(event, listener ) »

Remove a listener for an event.

This method is slightly different than the one of events.EventEmitter. - If no argument is provided to off(), all listeners of the document will be removed.
- If only an event is provided, all listeners for this event will be removed.
- If an event and a listener are provided, the listener will be removed from the event provided.

Document.removeAllListeners( event ) »

Remove a listener for a particular event. If no argument is provided, it willremove all the listeners for all events.

Document.setMaxListeners( n ) »

Set the maximum of listeners.
Method from events.EventEmitter.

Document.listeners( event ) »

Returns all the listeners for this event. These listeners can be

{
    once: true,
    listener: listener
}

If raw is set to false (default is true), the objects are replaced by the listener they contain.

__Document.emit(event, [arg1], [arg2], [...]) »

Execute each of the listeners in order with the supplied arguments.

Internal methods

Note: More docs are coming...

Model

Model.compile( name, schema, settings, thinky )

This method is called by Thinky.createModel and is the core that creates models.

Model.createBasedOnSchema( result, doc, originalDoc, enforce, prefix, schema )

Create an instance of a model based on doc.

Model.checkType( result, doc, originalDoc, schema, key, type, typeOf, prefix, enforce )

For every key of an object provided to create an instance of a model, we are going to check the type of the value and see if it is a valid one or not.

Model._execute( query, callback ) »

Similar to Model.execute but just call callback without wrapping it.

Document

Document.getDocument( ) »