【问题标题】:Getting count of rows from Knex从 Knex 获取行数
【发布时间】:2021-12-01 05:58:28
【问题描述】:

我有一个异步函数试图返回表“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}` });
        }
    }
)

但是,我收到一个错误,并且无法在 Internet 上找到任何相关信息。

Something went wrong. error: select * from "posts" where "id" = $1 limit $2 - invalid input syntax for type integer: "count"

会发生什么?

【问题讨论】:

  • 在这种情况下db是什么?
  • db 是一个用于与数据库通信的 Knex 对象。有了它,您可以访问 Postgresql 表、触发器等。

标签: javascript postgresql knex.js


【解决方案1】:

knex.js 查询构建器的结果是数组。 查询可能会成功,并且只返回 0 个结果。

此外,您可以尝试直接在列名中使用该列的别名(或 count() 调用)。像这样的:

async getPostCount() {
    return db('posts').count('id as CNT').first()
}

....

 await PostsService.getPostCount()
                    .then(result => {
                        res.json({
                            count: result.CNT,
                            token: req.query.secret_token
                        })
                    })
    

【讨论】:

  • 谢谢,这让我走得更远,我发现还有另一个 API 调用与我的 count 调用相同,这让 API 感到困惑。
  • 您将如何只计算“is_complete”列上为 true 的记录?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2017-09-20
  • 2022-01-18
  • 1970-01-01
  • 2021-05-11
相关资源
最近更新 更多