簡體   English   中英

從 Knex 獲取行數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM