Nodejs显示的是一个记录,而不是三个。
我在posts表下的数据库中有3条记录,但是下面的nodejs代码仅显示一条记录,而不是3条记录。我将不胜感激。有人可以帮我解决这个问题。
JSON {'id': 1, 'completed': False, 'title': 'delectus aut autem', 'userId': 1}
Traceback (most recent call last):
File "./test.py", line 25, in <module>
json = json.loads(request.decode('utf-8'))
AttributeError: 'dict' object has no attribute 'loads'
答案 0 :(得分:1)
您要声明循环内的obj更改范围,请尝试
exports.display = function (req, res) {
var userid = 5;
db.query('SELECT * FROM posts', function (error, results, fields) {
if (error) {
res.json({
message: 'issue with query'
})
} else {
var objs = []; // <= Declare objs here
var resultCount = results.length; // <= Declare count of total queries here
successfulQueries = 0; // <= Increase this when a callback is called
results.forEach(function (row) {
var postid = row.id;
var title = row.title;
var content = row.content;
var type = -1;
console.log(title);
db.query('SELECT count(*) as cntStatus,type FROM like_unlike WHERE postid=?', [postid], function (error, results, fields) {
successfulQueries++;
const total_count = results[0].cntStatus;
objs.push({
id: postid,
title: title,
content: content,
like: total_count
});
if (resultCount === successfulQueries) {
res.end(JSON.stringify(objs));
console.log('Finish');
}
})
});
}
});
}