very_naisu
very_naisu

Reputation: 109

How to properly use knex.js query builder and its .first() method

I am having a bit of trouble with knex.

I am getting an error that says

Cannot chain .first() on "first" query

Currently, my controller calls a function in a repository with the code below:

exports.findByEmail = async (email) => {
    return knex
        .where({email: email})
        .first();
}

This code works the first time around, grabbing the correct information, but on the consecutive call, the above error is thrown.

My knex is instantiated with a table already.

I've tried it this way, with the then chained to the back, and still end up with the same result. https://github.com/knex/knex/issues/1355

exports.findByEmail = async (email) => {
    return knex
        .where({email: email})
        .first()
        .then(row => row);
}

Here is how I call it:

let user = await CustomerRepo.findByEmail(req.body.email)

What am I doing wrong? Thank you

Upvotes: 1

Views: 2148

Answers (1)

very_naisu
very_naisu

Reputation: 109

I've figured out what I did wrong. It is how I instantiated it.

I instantiated knex like this:

const knexQB = require('knex')
const knex = knexQB(config)('table_name');

And called it like above

return knex.where().first();

But thats wrong, as I have to instantiate knex per query like this

return knex('table_name').where().first();

I can't instantiate it for the entire class as it seems knex's querying doesn't just stop the query after returning the result.

The more you know! Thanks again.

Upvotes: 6

Related Questions