我想使用knex和MySQL进行计数并将计数值保存到变量中。下面是我的代码段。我使用邮递员进行请求
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." })
})
})
这将返回我:
[
{
"COUNT(id_proj)": 0 //or 1 of the record is in table
}
]
我的问题是如何将结果存储到变量中?根据{{1}}的结果,我要查询是select count
还是大于0来进行另一个查询。谢谢您的时间!
答案 0 :(得分:1)
我尝试以另一种方式解决此问题,摆脱了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." })
})
希望这对某人有帮助。
答案 1 :(得分:1)
您的knex查询中可能有一个错误,请尝试以下操作:
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 */});
}
});