Node js + postgresql:使用带有多个postgresql的Node.js生成JSON

时间:2015-05-22 12:49:55

标签: json node.js postgresql

我刚开始用node.js编码,我知道node.js是异步的,但不知道如何处理这个问题。 我正在查询postgresql并构建一​​个JSON,如下所示,

我添加了我的代码:

@{ $valid_values[0] }

但是我收到了错误:

var express = require('express');
var router = express.Router();
var pg = require('pg');
var client = require('../routes/database.js');
var cookieParser = require('cookie-parser');
var dateFormat = require('date-format');
var async = require('async');
var today = dateFormat(new Date());


router.post('/conversation/my', function(req, res) {
    var userId = 59;
    var limit = 10;
    var offset = 0;

    var postgresql = "select id from conversation where party_id = '" + userId + "' and reply_id = 0 order by created_on desc limit " + limit + " offset " + offset + "";
    var postsJSON = { };
    var arr = new Array();

    client.query(postgresql, function(err, data) {
        if (err) {
            console.log(err);
            return rollback(client);
        }
        var rows = data.rows;
        for ( i = 0; i < rows.length; i++) {
            var post = rows[i];
            var post_obj = {};
            post_obj.id = post.id;
            getConversationResponse(post.id, function(err, res) {
                if (!err) {

                     post_obj.actor = res;
                     arr.push(post_obj);
                     console.log(JSON.stringify(arr));
                     res.send({
                          data : arr
                     });

                }

            });

        }

    });

});

function getConversationResponse(conversation_id, cb) {
    client.query('SELECT * FROM people WHERE id ='+conversation_id+';', function(err, actor) {
    client.query('SELECT * FROM users WHERE id ='+conversation_id+';', function(err, user) {
      var actor_obj = {};
      actor_obj.id = user.id;
      actor_obj.name = user.name;
      actor_obj.email = user.email;
      client.end();
      cb (null,actor_obj);
    });
    });
}

module.exports = router;

1 个答案:

答案 0 :(得分:0)

您的client.end();不应该在功能中。它应该在第一个client.query之后完成对话。目前发生的情况是,对于每个对话,您调用该函数来获取人/用户,您终止客户端。所以下一个对话行无法获得人/用户。

另外,理想情况下,您应该加入三个表并一次性获取所有数据。

var postgresql = "select id, people.*, users.* from conversation, people, users where party_id = '" + userId + "' and people.id=conversation.id and users.id=conversations.id and reply_id = 0 order by created_on desc limit " + limit + " offset " + offset + "";