node mysql json,将node-mysql结果行合并为单个JSON返回node.js

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

}

});

}

});

解决方案

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

}

});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值