[英]Getting count of rows from Knex
我有一个异步函数试图返回表“posts”中的行数
async getPostCount() {
return db('posts').count('id');
}
这在 API 中使用...
router.get(
'/count',
async (req, res, next) => {
try {
await PostsService.getPostCount()
.then(result => {
res.json({
count: result,
token: req.query.secret_token
})
})
.catch((err) => {
throw(err);
});
}
catch (err) {
console.log(err);
res
.status(500)
.json({ success: false, msg: `Something went wrong. ${err}` });
}
}
)
但是,我收到一个错误,并且无法在互联网上找到任何关于它的信息。
Something went wrong. error: select * from "posts" where "id" = $1 limit $2 - invalid input syntax for type integer: "count"
会发生什么?
knex.js 查询构建器的结果是数组。 查询可能会成功并且只返回 0 个结果。
此外,您可以尝试直接在列名(或 count() 调用)中为列使用别名。 像这样的东西:
async getPostCount() {
return db('posts').count('id as CNT');
}
....
await PostsService.getPostCount()
.then(result => {
res.json({
count: result[0].CNT,
token: req.query.secret_token
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.