How to ignore a column update if not exist using knex?

Viewed 968

I'm trying to update a table using this syntax

knex(tableName)
.where("id", "=", userId)
.update({
  [payment]: userPayment,
  exampleColumn: userInput,
})
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))

now exampleColumn may exist in some tables or not so i'm in a situation that i want to make this dynamic as possible

is there a syntax equal to this

.update({
  [payment]: userPayment,
  exampleColumn?: userInput, // ? to update if exist if not ignore this line
})

as work around i added a condition to my code

if (!isExampleColumn) {  /* I get this from a another function */
  userInput = undefined;
}

knex(tableName)
.where("id", "=", userId)
.update({
  [payment]: userPayment,
  exampleColumn: userInput, // if userInput is undefined then it will be ignored
})
.then((_result) => {console.log(_result);})
.catch(err => console.error(err))

but i think there is a better solution than this.

1 Answers

You can use conditional spread, it looks like:

knex(tableName)
  .where("id", "=", userId)
  .update({
    [payment]: userPayment,
    ... isExampleColumn? {exampleColumn: userInput} : {},
  })
  .then((_result) => {console.log(_result);})
  .catch(err => console.error(err))

Since Knex is a QueryBuilder, you can also split the "building" parts.

const query = knex(tableName)
.where("id", "=", userId)
.update({
  [payment]: userPayment,
});

if(isExampleColumn) {
  query.update({exampleColumn: userInput})
}

const results = query
  .then((_result) => {console.log(_result);})
  .catch(err => console.error(err))

Related