使用节点js检查数据库是否有数据,我的if语句出了什么问题?

时间:2018-02-06 05:02:07

标签: mysql node.js

我正在尝试查看用户是否互相关注或已经喜欢帖子,以便我可以呈现没有错误的页面。我得到的是,如果数据库中没有数据(用户没有关注帖子作者或喜欢当前帖子),我将收到错误,我的应用程序将崩溃: TypeError:无法读取属性' user_id'未定义的

我做了一个if语句,但它似乎没有用。我在另一个只有一个SELECT查询的路由上做了一个if语句,它运行正常。我不知道我哪里出错......

我的代码:

if (req.user) { // if the user is currently logged in
  var q = 'SELECT * FROM follows WHERE followee_id =\'' + author_id + '\' AND follower_id =\'' + req.user.id + '\'';
  connection.query(q, function (err, resault) {
    if (err) {
      console.log(err);
    }
    var isfollowing = {
      follower_id: resault[0].follower_id,
      followee_id: resault[0].followee_id
    };

    var q = 'SELECT * FROM likes WHERE user_id =\'' + req.user.id + '\' AND post_id =\'' + post_id + '\'';
    connection.query(q, function (err, likes) {
      if (err) {
        console.log(err);
      }
      var hasLikes = {
        user_id: likes[0].user_id,
        post_id: likes[0].post_id
      };

      if ((likes.length > 0) && (resault.length > 0)) { // if the user has likes and is following users
        console.log('has likes, has follows');
        res.render('single', {
          showPost: post,
          comments: comments,
          numComments: numComments,
          hasLikes: hasLikes,
          likes: likes,
          isfollowing: isfollowing,
          resault: resault
        });

      } else if ((likes.length < 0) && (resault.length > 0)) {
        res.render('single', {
          showPost: post,
          comments: comments,
          numComments: numComments,
          isfollowing: isfollowing,
          resault: resault,
          likes: likes
        });
        console.log('NO likes, has follows');

      } else if ((likes.length > 0) && (resault.length < 0)) {
        console.log('has likes, NO follows');
        res.render('single', {
          showPost: post,
          comments: comments,
          numComments: numComments,
          hasLikes: hasLikes,
          resault: resault,
          likes: likes
        });

      } else {
        console.log('has nothing');
        res.render('single', {
          showPost: post,
          comments: comments,
          numComments: numComments,
          resault: resault,
          likes: likes
        });

      }
      console.log(isfollowing);
      console.log(hasLikes);
    });

  });
}

1 个答案:

答案 0 :(得分:0)

发现我的错误。

我使用的是:

likes.length < 0

检查数组是否为空,我应该使用它:

!likes.length