點燈坊

失くすものさえない今が強くなるチャンスよ

Using Knex to UPDATE Data

Sam Xiao's Avatar 2021-11-04

Although we can use raw SQL UPDATE, but it’s more concise to use Knex to update data.

Version

Knex 0.95.12

Knex

import Knex from 'knex'

let knex = Knex ({
  client: 'pg',
  connection: {
    host: 'localhost',
    port: 5432,
    user: 'admin',
    password: '12345',
    database: 'DBLab'
  },
  searchPath: ['public']
})

let result = await knex ('articles')
  .update ({
    'title': 'Title 2',
    'content': 'Content 2'
  }, ['*'])
  .where ({ id: 1 })

console.log (result)

Line 15

let result = await knex ('articles')
  .update ({
    'title': 'Title 2',
    'content': 'Content 2'
  }, ['*'])
  .where ({ id: 1 })

Use Knex to generate SQL UPDATE and return result :

  • knex : table to update
  • update : Object to update, key is field and value is data
  • ['*'] : return whole Object after updated, this is optional
  • where : where condition for =, key is field and value is data

Becuase Knex will return Promise, we have to use top-level await to deal with Promise.

update000

Conclusion

  • Update Object is more intuitive than raw SQL UPDATE, and more concise

Reference

Knex, update