Search code examples
mysqlnode.jsknex.js

save SELECT COUNT into variable using mysql and knex


I want to do a count using knex and MySQL and save the count value into a variable. Down below is a snippet of my code. I use postman for requests

router.post('/insertNewProject', (req, res) => {
    knex
      .raw('SELECT COUNT(id_proj) FROM project WHERE projectName=?', [req.body.projectName])
      .then((count) => {
        res.json(count[0])
      })
      .catch(() => {
        res.json({ success: false, message: "Please try again later." })
      })
})

This will return me:

[
    {
        "COUNT(id_proj)": 0  //or 1 of the record is in table
    }
]

My question is how can I store the result into a variable? Based on the result of the select count, I want if it's =0 to do a query and if it's greater than 0, to do another query. Thank you for your time!


Solution

  • You probably have an error in your knex-query, try this:

    router.post('/insertNewProject', async (req, res) => {
        const result = await knex('project')
            .count('id_proj as count')
            .where({projectName: req.body.projectName})
            .first()
            .catch(() => res.json({
                success: false,
                message: "Please try again later."
            }));
    
        if (result.count === 0) {
            // Perform some query
            return res.json({/* Some response */});
        } else {
            // Perform another query
            return res.json({/* Some response */});
        }
    });