Combining node-mysql result rows into single JSON return for node.js

风流意气都作罢 提交于 2019-12-21 21:37:16

问题


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) {

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));
            }
        });
    }
});

回答1:


Asked and answered.

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);
        }
    });

}



来源:https://stackoverflow.com/questions/17913916/combining-node-mysql-result-rows-into-single-json-return-for-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!