在mySQL之后无法从JSON获得价值

时间:2014-06-01 08:39:56

标签: mysql json node.js express

var sender_username = req.session.user_id;
var recipient_username = req.body.recipient_username; 
var content = req.body.content; 

var sql = ' SELECT sender_username, recipient_username, COUNT(recipient_username) as count FROM message WHERE sender_username = "'+sender_username+'" AND recipient_username = "'+recipient_username+'" GROUP BY sender_username LIMIT 1 ';
var message_no = 0;
var data;

connection.query(sql, function(err, result) {
    if (err) {
        res.send(err);
    }
    else {
        data = result; 
        // res.send(data); < - this works
        // res.send(result); <- this works
        // res.send(result.count); <- undefined
    }
});

res.send(data); // undefined (can't seem to save to variable after connection.query())

res.send(result);似乎有效。它给出了:

[{"sender_username":"sender","recipient_username":"recipient","count":2}]

我只是想获取count的值并将其保存到变量中,但result.count之类的东西由于某种原因返回undefined。

1 个答案:

答案 0 :(得分:1)

因为JSON是一个数组,所以你应该像下面那样访问它

res.send(result[0].count);