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

允我心安 提交于 2019-12-04 17:41:06

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

}

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