返回undefined的对象属性(nodejs)

时间:2014-11-13 12:29:55

标签: node.js express pagination

我在expressjs应用程序的分页函数中工作。此函数接收分页参数并返回包含某些信息的对象。其中一个是查询的总结果(postgresql db)。但是当我执行时,所有数据都正确返回,除了这个总数。

分页功能:

var Pagination = function (obj, cb) {

    var base = require("./modulo-conn");
    var queryTotalReq = "SELECT COUNT(*) AS TOTAL FROM (" + obj.query + ") AS T";
    var objQry = {
        db: obj.db,
        query: queryTotalReq
    };

    this.current = obj.paging.Actualpage;
    this.next = obj.paging.Actualpage + 1;
    this.prev = ( obj.paging.Actualpage > 0) ?obj.paging.Actualpage - 1 : obj.paging.Actualpage;

    base.query(objQry, null, function(data){
        this.totalPg = data[0].TOTAL;
    });

   cb(this);
};


var postOpt = {
        db: 'postgres',
        query: 'SELECT NOW() as when',
        paging:{
            itemPerPage: 20,
            Actualpage:2
        }
    };

var b = null;  

Pagination(postOpt, function(data){
    b = data;
});  

console.log(b);

连接数据库功能:

module.exports.query = function(postOpt, mongoOpt, cb){
if(postOpt){

        var conString =     "postgres://"+conn[postOpt.db].login+":"+conn[postOpt.db].passwd+"@"+conn[postOpt.db].server+":"+conn [postOpt.db].port+"/"+postOpt.db;//connection string

        var pg = require('pg');

        console.log('connect to postgresql...');
        pg.connect(conString, function(err, client, done){
            if(err){
                console.log(err);
                return false;
            } 

            client.query(postOpt.query, function(err, result) {
                done();
                if(err) {
                    return console.error('error running query', err); 
                }
                cb(result.rows);  
            });  
            done();
        });
    }else{
        console.log('Database type not defined or not found!');
    }
};

1 个答案:

答案 0 :(得分:0)

乍一看,你只需要在base.query中调用cb(),

    var Pagination = function (obj, cb) {
      var _this = this;
      var base  = require("./modulo-conn");
      var queryTotalReq = "SELECT COUNT(*) AS TOTAL FROM (" + obj.query + ") AS T";
      var objQry = {
        db: obj.db,
        query: queryTotalReq
      };

      _this.current = obj.paging.Actualpage;
      _this.next    = obj.paging.Actualpage + 1;
      _this.prev    = (obj.paging.Actualpage > 0) ? obj.paging.Actualpage - 1 : obj.paging.Actualpage;

      base.query(objQry, null, function(data){
        _this.totalPg = data[0].TOTAL;
        cb(_this);
      });
    };