我试图通过MySQL表中的每个帖子来运行,获取用户名,在单独的表中运行单独的查询以从该用户获取信息如配置文件img等,然后把它放在JSON中。NodeJS SQL在for循环中返回'Can not read property'x'undefined'
这项工作,直到我尝试和增加另一个查询用于获取用户信息,然后返回
'Cannot read property 'postId' of undefined'
我试过很多方法可以解决该,但他们都没有工作。
这里是我的代码:
var postLocation = req.query.postLocation.replace(regex, escaper);
connection.query("SELECT * FROM `posts` WHERE (postLocation = '" + postLocation + "' OR postLocation = 'Global') AND postDeleted = 'no' ORDER BY postId DESC;", function (err1, rows1, fields1) {
if(err1){
res.send(err1);
} else if(!rows1.length){
res.send('{"rapids": [{"response": "This post does not exist."}]}');
} else {
var queryString = "";
var queryTimes = 0;
var profileURL = null;
for(i = 0; i < rows1.length; i++){
queryTimes++;
connection.query("SELECT * FROM `users` WHERE username = '" + rows1[0].postBy + "' ORDER BY postId DESC;", function (err2, rows2, fields2) {
queryString = queryString + '{"postId": "' + rows1[i].postId + '", "post": "' + rows1[i].post + '", "postBy": "' + rows1[i].postBy + '", "postLikes": ' + rows1[i].postLikes + ', "postByProfileImgURL": "' + rows1[i].postByProfileImgURL + '", "postDate": "' + rows1[i].postDate + '", "postViews": ' + rows1[i].postViews + ', "postDeleted": "' + rows1[i].postDeleted + '"';
if(queryTimes == rows1.length){
queryString = queryString + '}';
} else {
queryString = queryString + '}, ';
}
});
}
res.send('{"rapids": [' + queryString + ']}');
}
});
谢谢!
碰碰因为 –