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 updateupdate
: Object to update, key is field and value is data['*']
: return whole Object after updated, this is optionalwhere
: 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.
Conclusion
- Update Object is more intuitive than raw SQL UPDATE, and more concise