Home > database >  Knex query saved to a variable and modified does not work with mapped conditions
Knex query saved to a variable and modified does not work with mapped conditions

Time:10-12

I have a knex query that I have saved to a variable so I can reuse it easily.

When I modify this query and map conditions to it, it doesn't work.

const query = db.select('*').from('users');

const users = await Promise.all(['John', 'Doe'].map((firstName) => query.modify((builder) => builder.where({ firstName }))));

If I pass in the query itself directly, like below, it works:

const users = await Promise.all(['John', 'Doe'].map((firstName) => db.select('*'). from('users').modify((builder) => builder.where({ firstName }))));

How can I get this to work with the query saved to a variable?

CodePudding user response:

The problem was that the query was being permanently modified so it runs with all the conditions rather than one condition per time.

This would work because the query is only modified once (there's only one item in the array):

const users = await Promise.all(['John'].map((firstName) => query.modify((builder) => builder.where({ firstName }))));

If you want to map different conditions when reusing a partial query, then you should clone the query each time before running:

const users = await Promise.all(
    ['John', 'Jane', 'Doe'].map((firstName) => {
        const temp = query.clone();
        temp.modify((builder) => builder.where({ firstName }));
    }),
);
  • Related