将node-mysql结果行合并为单个JSON返回node.js [英] Combining node-mysql result rows into single JSON return for node.js

查看:614
本文介绍了将node-mysql结果行合并为单个JSON返回node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道返回一堆JSON的最佳方式,这是一些依赖的mysql查询的结果。

I want to know the best way to return a bunch of JSON that is the result of some dependent mysql queries.

app.get('/viewing/:id', function (req, res){
    if(!req.cookies.user) {
        res.end('Requires Authenticated User');
    } else {   
        connection.query('SELECT blah blah where userId='+req.params.id,
        function (error, rows, fields) {

现在我们有了一堆行 - 我说需要经过每一个,并根据数据进行另一个mysql查询所以我最终需要重复调​​用(我循环?)

Now we have a bunch of rows -- lets say 5. I need to go through each one and make another mysql query based on the data I just got. So I end up needing to repeat call (do I loop?)

            connection.query('SELECT id, firstName, lastName from users where id='+AN_ID_FROM_PRIOR_QUERY,
            function (error2, rows2, fields2) {

             });
           }
        }

如何将第二个查询的每个重复选择的行合并到单个对象中, ?

How do I combine the rows from each of the repeated selects of the second query into a single object that can be returned as JSON?

            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(JSON.stringify(results));
            }
        });
    }
});


推荐答案

Async.js实用工具有许多好东西,包括地图功能 underscores.js 帮助整理任何内容!

The Async.js utility has lots of good stuff including a map function and underscores.js helps tidy anything up!

app.get('/viewing/:id', function (req, res){
  if(!req.cookies.user) {
      res.end('Requires Authenticated User');
  }
  else {
     connection.query('SELECT something,somethingelse from mytable where userId = ?',[req.params.id], function (error, rows, fields) {
        async.map(rows, getUsers, function(err, results){
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end(JSON.stringify(_.flatten(_.compact(results))));
         });
     });
  }
});

function getUsers(user, callback) {
    connection.query('SELECT id,firstName,lastName FROM users WHERE id = '+ user.otherId,  function(err, info) {
        if(err) {
            console.log(err);
            return callback(err);
        }
        else {
           return callback(null, info);
        }
    });

}

这篇关于将node-mysql结果行合并为单个JSON返回node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆