0

i've written a simple module to handle my couchdb CRUD operations using nano, however i'm having hardship returning from the results i query from the couch database. My Code is as follows. couchdb.js

//Select from couch view
exports.couchSelect=function (_db, document,view) {
    return _db.view(document, view,function(err, body){

            if(!err){
                var rows = body.rows; //the rows returned
                console.log(rows);
                return rows;
            }else{
                console.log(err);
            }

        }
    );
}

routes.js

var couchdb = require('./couchdb');
app.get("/orders", function (req, res) {
    var db = couchdb.couchConnect('ezyextension_orders');
    var insert = couchdb.couchSelect(db, 'orders', 'orders');
    console.log(insert);
});

On executing the returned output is only get Node http request parameters without the returned rows, need help to return the actual JSON rows queried.Thanx

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Isaac Obella
  • 2,613
  • 2
  • 16
  • 29

2 Answers2

0

You're using nano which use callback to make async calls. Returning _db.view only return a void function. I added comments to tell you what is happening :

exports.couchSelect = function(_db, document, view) {
    _db.view(document, view, function(err, body) {
        //This will be called after the couchSelect request.
        if (!err)
            console.log("Callback : " + body.rows);
    });
}


//When you use it

var couchdb = require('./couchdb');
app.get("/orders", function(req, res) {
    var db = couchdb.couchConnect('ezyextension_orders');
    var insert = couchdb.couchSelect(db, 'orders', 'orders');
    //This is synchronous. This will be called before the callback is called.
    console.log(insert);
});
Alexis Côté
  • 3,670
  • 2
  • 14
  • 30
0

I decided to use blue-nano which uses promises instead of callbacks and the code is as below. couchdb.js

var nano = require('nano-blue')('http://localhost:5984');
//Select from couch view
exports.couchSelect=function (_db, document,view) {

    return _db.view(document, view);

}

routes.js

    app.get("/orders", function (req, res) {
    var db = couchdb.couchConnect('ezyextension_orders');
    couchdb.couchSelect(db, 'orders', 'all').spread(function (body,header) {
        res.send(body.rows);
    }).catch(function(err) {
        console.log(err.message);
    });

});

This works perfectly

Isaac Obella
  • 2,613
  • 2
  • 16
  • 29