1

I using the postgresql in node application and knex.

I want to add text to exist field

for example if the field has value "abc" I want to add the "DEF" to "ABC" ==>"abcDEF"

in BASE SQL it is look like that: update set = [fieldname] + 'new text' this is my code that doesn't work

var password ={my full object}
password.versions = `[versions]  || ${password.versions}`;
        return  db('passwords')
                .where({
                    id: id,
                    deleted: false,
                    active: true
                })
                .update(password);
24sharon
  • 1,859
  • 7
  • 40
  • 65
  • FOUND password.versions = db.raw(`?? || '${password.versions}'`, ['versions']) ; FROM https://stackoverflow.com/questions/42212497/knex-js-how-to-update-a-field-with-an-expression – 24sharon Nov 05 '18 at 17:28

1 Answers1

1
  1. Ok, you are basically are looking for String concatenation operator || for this purpose.
  2. Any custom select/insert/update logic that is not supported by knex can be written using knex.raw. Or event the whole query.

Full example here:

const password = {
  // ...rest of the fields
  versions: 'DEF',
};
const update = Object.assign({}, password, {
  versions: knex.raw('versions || ?', password.versions)
})
const builder = knex('passwords')
  .update(update)
  .where({
    id: id,
    deleted: false,
    active: true
  });
console.log(builder.toString()); // => update passwords set versions = versions || ? 
coockoo
  • 2,294
  • 17
  • 26