Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

291
Views
Getting count of rows from Knex

I have a async function that is attempting to return a count of rows in a table "posts"

async getPostCount() {
    return db('posts').count('id');
}

This is used in an 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}` });
        }
    }
)

However, I get an error and have not been able to find anything on the internet about it.

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

What could be going on?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The results from knex.js query builders are arrays. A query could be successful and simply return 0 results.

Also, you can try using an alias for the column directly in the column name (or count() call). Something Like this:

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
                        })
                    })
    
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!