Tenzolinho
Tenzolinho

Reputation: 982

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!

Upvotes: 4

Views: 5179

Answers (2)

Ihor Sakailiuk
Ihor Sakailiuk

Reputation: 6068

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 */});
    }
});

Upvotes: 4

Tenzolinho
Tenzolinho

Reputation: 982

I tried to solve this in a different way, getting rid of select count:

 knex
    .select('*')
    .from('project')
    .where('projectName', '=', req.body.projectName)
    .then((count) => {
      if (count == 0) {
          // do query1
      } else {
          // do query2
      }
    })
    .catch(() => {
      res.json({ success: false, message: "Please try again later." })
    })

Hope this helps someone.

Upvotes: 1

Related Questions