Customizing Document's Key

To create custom key generation strategy your constructor function must include require('kouchbase-odm').Key.prototype in its prototype chain.
See Key API Reference for details about abstract methods and methods which may be overriden.

    const util         = require('util');
    const couchbaseODM = require('kouchbase-odm');
    const Key          = couchbaseODM.Key;

    /*
     * constructor
     *
     * the constructor will be called with options which were set when defining
     * a Model (or CouchbaseODM instance)
     * @param {Object}         options
     * @param {string|integer} options.id
     * @param {string}         options.prefix=defaults to Model's name
     * @param {string}         options.postfix=""
     * @param {string}         options.delimiter="_"
     */
    function UUID1Key(options) {
        Key.call(this, options);
    }

    //every key generation strategy must expose static `dataType` property
    // which determines data type of document's `id`. Usually it will be
    // `string` or `integer`
    UUID1Key.dataType = 'string';

    //behavior delegation - adds `Key.prototype` to `UUID1Key`'s prototype chain
    util.inherits(UUID1Key, Key);

    /**
     * generate
     *
     * generates new key
     * The method must return a prosime with generated `Key` object (self)
     *
     * @param {Instance} instance - document object
     * @return {Promise<UUID1Key>}
     */
    UUID1Key.prototype.generate = function(instance) {
        const id = uuid.v1();
        this.setId(id); //see Key.setId for more information
        return Promise.resolve(this);
    };

the generate method is always run with document object (Instance) the key is generated for.

The above example just generates custom id value (dynamic part of a key of a document). You could take control over whole key string format by overriding the toString method of the Key prototype.

Using custom Key

So now when you've created the custom generation strategy you can use it simply like:

    const User = couchbase.define('User', {
        type: 'object'
    }, {
        //options object
        key: UUID1Key  // ==> provide constructor function object as the option when defining a Model
    });

NOTE: The same procedure applies for providing custom key generation strategy of reference document keys (refDocKey option on a Model)

comments powered by Disqus