var Promise = require('bluebird')
var request = Promise.promisifyAll(require('request'))
var jade = require('jade')
var _ = require('lodash')

module.exports = {
    process: function(blk){
        var qstring = _.get(blk,'body','').trim()

        return Promise
            .resolve([{foo:1},{foo:2}])
            .then(function(data){
                this.ctx.data = data
                var locals = {
                    code: qstring
                }
                return jade.renderFile(__dirname + '/mongoquery.jade', locals)
            }.bind(this))
    }
}

@@ -19,17 +19,17 @@
 ire(
-'
+%22
 bluebird
 ')%0Av
@@ -28,118 +28,506 @@
 bird
-')
+%22);
 %0Avar 
-request = Promise.promisifyAll(require('request'))%0Avar jade = require('jade')%0Avar _ = require('lodash')
+using = Promise.using;%0Avar jade = require(%22jade%22);%0Avar _ = require(%22lodash%22);%0Avar mongodb = Promise.promisifyAll(require(%22mongodb%22));%0Avar MongoClient = mongodb.MongoClient;%0Avar MongoError = mongodb.MongoError;%0Avar url = process.env.MongoDB_URL %7C%7C %22mongodb://localhost:27017/apps%22;%0Avar collectionName = process.env.MongoDB_COLLECTION %7C%7C %22listings%22;%0A%0Afunction connect() %7B%0A  return MongoClient.connectAsync(url)%0A    .disposer(function(connection, promise) %7B%0A      connection.close();%0A    %7D);%0A%7D
 %0A%0Amo
@@ -543,18 +543,16 @@
 rts = %7B%0A
-  
   proces
@@ -567,22 +567,19 @@
 ion(blk)
+ 
 %7B%0A
-    
     var 
@@ -602,25 +602,27 @@
 blk,
-'
+ %22
 body
-',''
+%22, %22%22
 ).trim()
 %0A%0A  
@@ -621,79 +621,232 @@
 im()
-%0A%0A        return Promise%0A            .resolve(%5B%7Bfoo:1%7D,%7Bfoo:2%7D%5D)
+;%0A    console.log(%22Received query: %22 + qstring);%0A    var query = JSON.parse(qstring);%0A    return using(connect(), function(db) %7B%0A        return db.collection(%22listings%22)%0A          .find(query)%0A          .toArray();
 %0A      
+%7D)%0A
     
@@ -867,16 +867,17 @@
 on(data)
+ 
 %7B%0A      
@@ -878,24 +878,16 @@
         
- 
-       
 this.ctx
@@ -898,25 +898,18 @@
 a = data
+;
 %0A
-        
         
@@ -923,26 +923,16 @@
 als = %7B%0A
-          
         
@@ -959,32 +959,19 @@
     
-       
- %7D%0A      
+%7D;%0A
         
   re
@@ -962,26 +962,24 @@
  %7D;%0A        
-  
 return jade.
@@ -1001,17 +1001,17 @@
 rname + 
-'
+%22
 /mongoqu
@@ -1022,9 +1022,9 @@
 jade
-'
+%22
 , lo
@@ -1032,21 +1032,16 @@
 als)
+;
 %0A      
-      
 %7D.bi
@@ -1052,14 +1052,341 @@
 his))%0A  
+    .catch(MongoError, function(e) %7B%0A        console.error(%22Error: Failed to connect to MongoDB at: %22 + url,%0A          e.message);%0A      %7D)%0A      .catch(SyntaxError, function(e) %7B%0A        console.error(%22Error: Invalid find query %22, e.message);%0A      %7D)%0A      .catch(function(e) %7B%0A        console.error(%22Error: %22 + e)%0A      %7D);%0A
   %7D%0A%7D%0A

add connect to MongoDB and issue find queries