我尝试使用节点js从名为post的表中检索所有数据库记录,但问题是只检索了一条记录,而不是所有记录。在php中,我可以使用while()
循环遍历数据库记录来获取所有数据。
目前,我不知道如何在nodejs中整齐地循环数据库以获取数据库中的所有记录。一些Stackoverflow学者建议使用await/async方法,但我不知道如何在下面的代码中实现它。有人能帮我解决这个问题吗。
var connection = require('./config');
module.exports.getpost = function (req, res) {
connection.query('SELECT * FROM posts', function (error, results, fields) {
if (error) {
console.log('error');
res.json({
status : false,
message : 'there are some error with the query'
});
} else {
var postid = results[0].id;
var title = results[0].title;
var content = results[0].content;
var type = -1;
console.log(title);
// Checking user status
connection.query('SELECT count(*) as cntStatus,type FROM like_table WHERE userid= ? and postid=?', [userid,postid], function (error, results, fields) {
if (error) {
console.log('error');
res.json({
status : false,
message : 'there are some error with the query'
});
} else {
var total_count = results[0].cntStatus;
if(total_count > 0){
type = results[0].type;
}
var total_count = results[0].cntStatus;
var result = {
"id" : postid,
"title" : title,
"content" : content,
"type" : type,
"likes" : total_count
};
console.log('query okay');
res.json({
//data:results,
data : result
});
}
});
}
});
}
https://stackoverflow.com/questions/50594197
复制相似问题