Search code examples
mysqlnode.jsdelete-row

MySQL Node JS DELETE no working - 0 rows affected


I am trying to create a post route that will delete a user's data from several tables. I checked in mySQL workbench that the database user has this privilege. However when I click delete on the frontend, the queries appear to run but the rows do not get deleted. Can you someone please tell me where I am going wrong?

app.post('/disposal', redirectLogin, async(req, res) => {
      const user = res.locals;
      userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
      cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
      tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
      holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
      await connection.query(userStmt, (err, results) => {
        if (err) throw err;
        console.log(results);
        connection.query(holdingsStmt, (err, results) => {
          if (err) throw err;
          console.log(results);
          connection.query(cashStmt, (err, results) => {
            if (err) throw err;
            console.log(results);
          });
          connection.query(tradesStmt, (err, results) => {
            if (err) throw err;
            console.log(results);
          });
        });
      });
      req.session.destroy(err => {
        if (err) {
          return res.redirect("/dashboard");
        }
        res.clearCookie(SESS_NAME);
        res.send("Ninja disposed!");
      })
    })

Solution

  • You don't need to nest the calls if you are using async/await. As the res.locals is an object which contains the user property, you have to get the user property.

    You could get it by using Object destructuring syntax.

    Try this.

    app.post('/disposal', redirectLogin, async (req, res) => {
        const { user } = res.locals;
        userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
        cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
        tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
        holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
        try {
            let results = await connection.query(userStmt);
            console.log(results);
            let holdinResult = await connection.query(holdingsStmt);
            console.log(holdinResult);
            let cashResult = await connection.query(cashStmt);
            console.log(cashResult);
            let tradesResult = await connection.query(tradesStmt);
            console.log(tradesResult);
        } catch (error) {
            throw error
        }
        req.session.destroy(err => {
            if (err) {
                return res.redirect("/dashboard");
            }
            res.clearCookie(SESS_NAME);
            res.send("Ninja disposed!");
        })
    })