B
B
BEKa T2022-04-06 23:39:34
MySQL
BEKa T, 2022-04-06 23:39:34

How to get data from two or more tables in node js mysql?

I have 2 tables videosand comments
how to send their data to front? Need something like this

res.render('video/play', {
        video,
        comments
    }
});


// Video page
router.get('/:video', async (req, res, next) => {
  const userId = req.session.userId;
  const userLogin = req.session.userLogin;
  const videoId = req.params.video;
  if (!videoId) {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
    console.log('Error 404!!!');
  } else {
    try {
      // Показываю видео
      let sql = `SELECT * FROM videos WHERE id = '${videoId}';`;
      const queryToDB = await db.query(sql, (err, result) => {
        if (err) throw err;
        if (!result[0]) {
          // Если видео не найден
          res.json({
            ok: false,
            error: 'Video not found!'
          });
        } else {// Если видео найдено ПОКАЗЫВАЕМ
          // Подгружаю коменты
          let sql1 = `SELECT * FROM comments WHERE video = ${videoId}`;
          const queryToDB1 = await db.query(sql1, (err, result) => {
            if (err) throw err;
            if (!result[0]) {
              console.log('Comments not found!')
            } else {
              console.log(result)
            }
          });
          const video = result[0];
          res.render('video/play', {
            video,
            user: {
              id: userId,
              login: userLogin
            }
          });

          // Добавляем +1 к просмотрам видео
          let sql = `UPDATE videos SET views = views+1 WHERE videos.id = ${videoId} `;
          db.query(sql, (err, result) => {
            if (err) throw err;
          });
        }
      });
    } catch {
      throw new Error("Server error!")
    }
  }
})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question