Conditionally chaining a query object

I understand how to chain a data query object, e.g.:

import wixData from 'wix-data';

wixData.query("Customer")
  .gt("age", 20)
  .ascending("name")
  .limit(15)
  .find()
  .then( (results) => {
    //do something with results
  } );

However, I need to add to the chain based on another condition. I thought I could do this:

import wixData from 'wix-data';

let wixQuery = wixData.query("Profiles")
wixQuery.gt("age", 20)
wixQuery.ascending("name")

if (condition is met) {
  wixQuery.limit(10)
} else {
  wixQuery.limit(20)
 } 

wixQuery.find()
  .then( (results) => {
    //do something with results
  } );

However, while this doesn’t throw an error, it also doesn’t apply the query chain.

While the API documentation seems to suggest that this should be possible, all the examples show direct chaining rather than sequentially building a conditional chain, as I need.

Any help will be appreciated.

Try use:

let limit
if ( condition is met ) {
limit = 10
} else {
limit = 20
}
wixQuery = wixData . query ( “Profiles” ). gt ( “age” , 20 ). ascending ( “name” ).limit(limit)
.then()

or
Try to store the query…
let wixQuery = wixData . query ( “Profiles” ). gt ( “age” , 20 ). ascending ( “name” )
let query
if ( condition is met ) {
query = wixQuery . limit ( 10 )
} else {
query = wixQuery . limit ( 20 )
}

query . find ()
. then ( ( results ) => {
//do something with results
} );

Debug with console.log(results) in .then(…)

Thanks mvveiga. I realise now the example I used was imperfect to explain my problem. Your solution:

let limit
if ( condition is met ) { limit = 10 } else { limit = 20 }
wixQuery = wixData . query ( “Profiles” ). gt ( “age” , 20 ). ascending ( “name” ).limit(limit)
.then()

will work well in if I want limit to be either 10 or 20.

But I need to add or not add a .eq to the chain, e.g.:

import wixData from 'wix-data';

let wixQuery = wixData.query("Profiles")
wixQuery.gt("age", 20)
wixQuery.ascending("name")

if (condition is met) {
  wixQuery.eq("field", "value"
 } 

wixQuery.find()
  .then( (results) => {
    //do something with results
  } );

That is, if the condition is met, add the .eq to the chain; if the condition is not met, don’t add it.

So I’m trying to implement your second option, to store the query, progressively build it, then implement it - but so far haven’t been able to get to work.

I’ll keep trying as it seems intuitively obvious that it should work.