我尝试使用 Node js 从名为 post 的表中检索所有数据库记录,但问题是只检索一条记录而不是全部记录。
在 php 中,我可以使用 while()
循环来循环数据库记录以获取所有数据。
目前,我不知道如何在nodejs中巧妙地循环数据库以获取数据库中的所有记录。一些 Stackoverflow 学者建议使用 wait/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
});
}
});
}
});
}
最佳答案
我假设您正在使用 mysql npm。在这种情况下,我不确定你的情况有什么问题。结果参数是 select 语句返回的行数组。因此,您可以使用循环来迭代所有行。
您实际上并不需要使用 async/await (它在功能方面没有任何优势,但看起来更干净)。但是如果你想摆脱回调,你需要将连接查询包装到 Promise 中或使用具有 Promise 接口(interface)的 mysql2 npm。以下是如何使用 async/await 而不是回调来迭代选择中的所有行:
var connection = require('./config');
module.exports.getpost = async function (req, res) {
try {
const queryResult = await query('SELECT * FROM posts');
queryResult.forEach(row => {
console.log(row.title);
})
} catch (err) {
console.log('error');
res.json({
status: false,
message: 'there are some error with the query'
});
}
}
请注意,您需要使用nodejs 8来运行带有async/await的代码。
此外,您不需要在帖子查询中执行另一个查询,您可以使用 SQL 连接合并这两个查询
关于mysql - nodejs mysql查询仅显示一条记录而不是数据库中的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594197/