title: javascript method chaining, add methods from an array
body: <p>Hi I wondered whether you could help me build a method chain dynamically, I suspect this is easily done if you know how...</p>
  
  <p>Using mongoose and node.js I'm querying a mongo database.
  I use a function that I pass an object to which looks like this:</p>
  
  <pre><code>transaction = {
         model: a mongoose model
         req: Express.js request object
         res: Express.js response object
         query: a mongo db query eg, {_id:xxxxx}
         populate: [ {
           field: 'name_of_doc_field'
           select: 'field1,field2'
         } ]
      }
  </code></pre>
  
  <p>I'm constructing the query dynamically, and in the function I don't know how many fields I'll need to populate, or whether an offset or limit is required.</p>
  
  <p>I want to chain my find:</p>
  
  <pre><code>transaction.model.find(transaction.query).skip(offset).limit(limit).exec(function(err, collection_obj){...})
  </code></pre>
  
  <p>How do i build this chain dynamically, I'll need to test whether an offset was supplied in the test object, if it was add .skip method to the chain, etc, and with the populate method, there will be an array of items, each item in that array will need a new populate method adding to the chain.</p>
  
  <p>Finally, I'll need to an exec method to the end of the chain.</p>
  
  <p>Thanks for your help in advance</p>
  
  <pre><code>// Generated by CoffeeScript 1.4.0
      module.exports = {
        findMany: function(transaction) {
          var collection_obj, limit, offset;
          offset = parseInt(transaction.req.query.offset) || 0;
          limit = parseInt(transaction.req.query.limit) || 100;
          collection_obj = null;
          return transaction.model.find(transaction.query).skip(offset).limit(limit).exec(function(err, collection_obj) {
            return found(err, collection_obj, transaction.req, transaction.res);
          });
        },
      }
  </code></pre>