首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >nodejs mysql查询只显示一条记录,而不是数据库中的所有记录

nodejs mysql查询只显示一条记录,而不是数据库中的所有记录
EN

Stack Overflow用户
提问于 2018-05-30 07:06:22
回答 2查看 971关注 0票数 1

我尝试使用节点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

                    });
                }
            });
        }

    });
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-30 13:58:33

async瀑布-连续运行一组函数,每个函数将其结果传递给数组中的下一个函数。但是,如果任何函数将错误传递给回调,则不会执行下一个函数,而是立即调用带有错误的主回调。

var connection = require('./config');
var async = require('async');
module.exports.getpost = function (req, res) {
    var arrayOfFuncs = [];
    var func_1 = function(callback) {

        connection.query('SELECT * FROM posts', function (error, results, fields) {
            if (error) {
                console.log('error');
                callback(error, null); 
            } else {
                var toPass = {};
                toPass.postid = results[0].id;
                toPass.title = results[0].title;
                toPass.content = results[0].content;
                toPass.type = -1;
                callback(null, toPass); 
            }
        })
    }
    arrayOfFuncs.push(func_1);

    var func_2 = function(prevData, callback) {
        connection.query('SELECT count(*) as cntStatus,type FROM like_table WHERE userid= ? and postid=?', [userid,prevData.postid], function (error, results, fields) {
         if (error) {
                    console.log('error');
                    callback(error, null); 
                } 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');
                    callback(null, result); 
                }
            });
    }
    arrayOfFuncs.push(func_2);

    async.waterfall(arrayOfFuncs, function(errString, finalResult) {
        if(errString) {
            return res.send(errString);
        } else {
            return res.send(finalResult);
        }
    });
}
票数 0
EN

Stack Overflow用户

发布于 2018-05-30 07:44:22

我假设您使用的是mysql npm。那样的话,我不知道你的情况有什么问题。结果参数是select语句返回的行数组。所以你可以使用循环遍历所有的行。

你实际上不需要使用async/await (它在功能上没有任何优势,但看起来更干净)。但是如果你想摆脱回调,你需要将连接查询封装到promise中,或者使用具有promise接口的mysql2 npm。下面是如何使用async/await而不是callback遍历select中的所有行:

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的代码。

此外,您也不需要在posts查询中执行另一个查询,您可以使用SQL join合并这两个查询

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50594197

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档