NodeJS 尝试添加新的键和值到mysql结果对象,但没有工作,所以我的问题是如何添加新的键值并将其发送到客户端

v09wglhw  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(108)

我试图添加新的键值到mysql结果对象,但它现在工作如何修复它?
我正在尝试从post数据库获取所有post,并检查post_likes表中的post是否为like,如果为like,则在post请求对象中添加{isLike:true},否则为false

const fetchPost = (req, res, next) => {
  const sql = "SELECT account.name,account.username,post.content,post.likes, post.visibility,post.date,post.time, post.profile, post.id FROM post INNER JOIN account ON account.uid = post.user_id WHERE post.visibility = 'Friends' OR post.visibility = 'Public'";
  // const sql = "SELECT * FROM post";
  connectDB.query(sql, (err, post_result) => {
    if (err) {
      console.log(err);
      return next(createCustomError(err, 400));
    }
    const get_uid_query = `SELECT id FROM account where uid = '${req.user['uid']}'`;

    // get the id of user by uid
    connectDB.query(get_uid_query, (err, user_id_result) => {
      if (err) throw err;
      const id = (user_id_result[0]['id']);

      for (let i = 0; i < post_result.length; i++) {
        const sql = `SELECT user_id, post_id FROM post_likes WHERE post_id = ${post_result[i]['id']} AND user_id = ${id}`;
        connectDB.query(sql, (err, result) => {
          if (err) throw err;
          else if (result.length > 0) {
            post_result[i]['isliked'] = true;

          } else {
            post_result[i]['isLiked'] = false;  
          }
        })
      }
      res.status(200).json(post_result); // isLiked value not sending with the response how to fix it 
    })
  })
}
hgc7kmma

hgc7kmma1#

当您只需要一个查询就可以轻松获取信息时,您就不必要运行多个查询了。
我不是很熟悉node.js,所以这可能有错误:

const fetchPost = (req, res, next) => {
    const sql = `
        SELECT
            a.name, a.username, p.content, p.likes, p.visibility, p.date, p.time, p.profile, p.id,
            EXISTS(SELECT 1 FROM post_likes pl WHERE p.id = pl.post_id AND pl.user_id = (SELECT id FROM account WHERE uid = ?)) AS isLiked
        FROM post p
        INNER JOIN account a ON a.uid = p.user_id
        WHERE p.visibility = 'Friends' OR p.visibility = 'Public'
    `;
    
    connectDB.query(sql, [req.user['uid']], (err, post_result) => {
        if (err) {
            console.log(err);
            return next(createCustomError(err, 400));
        }

        res.status(200).json(post_result);

    })
}

相关问题