MySQL查询在NodeJS上返回一个空数组。为什么?

时间:2019-07-28 16:37:52

标签: mysql node.js

我正在尝试运行一个查询,该查询将向我返回有关特定事件的帖子以及对每个帖子的评论。当我运行查询时,由于某种原因,它会调用路由4次(为什么会这样?)。当我console.log结果时,我看到它第一次运行查询时,它返回了正确的结果,但是在接下来的三遍中,它返回了一个空数组。

这是我的代码:

async getEvent( req, res, next) {
    var username = req.session.passport.user.username;
    var id = req.params.id;

    // the queries below work fine and return the expected results
    var sql = "SELECT * FROM users JOIN profile_pictures WHERE email = ?;";
    sql += "SELECT * FROM project.events WHERE id = ?;";
    sql += "SELECT url FROM project.events JOIN project.event_images ON events.event_image = event_images.id WHERE events.id = ?;";

    console.log("Here!");

    await connection.query( sql, [username, id, id], function( err, results, fields) {
        if (err) 
                throw err;
        var curUser = results[0][0]; // save current user's data
        var event = results[1][0]; // save event
        var imageURL = results[2][0]; // get image url

       // every query before this line executes perfectly
       // THE FOLLOWING QUERY RETURNS EMPTY ARRAY            
        var getPostQuery = "SELECT * FROM project.posts JOIN project.comments ON posts.id = comments.post_id WHERE posts.event_id = ?";
        connection.query( getPostQuery, [id], function( err, results, fields) {
            if (err)
                throw err;
            var posts = results;

            console.log( posts.length); // return length of result array            
        })
    })
}

这是我得到的结果:

Here!
4
Here!
Here!
0
0
Here!
0

我已验证查询在工作台上返回正确的结果。如果您能指导我这里发生的事情,我会很乐意。

0 个答案:

没有答案