點燈坊

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

Using Knex to DELETE Data

Sam Xiao's Avatar 2021-11-04

Although we can use raw SQL DELETE, but it’s more concise to use Knex to delete 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')
  .delete (['*'])
  .where ({ id: 2 })

console.log (result)

Line 15

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')
  .delete (['*'])
  .where ({ id: 2 })

console.log (result)

Use Knex to generate SQL DELETE and return result :

  • knex : table to update
  • delete (['*']) : delete data and return whole Object after update, returning argument 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.

delete000

Conclusion

  • Delete is more intuitive than raw SQL DELETE, and more concise

Reference

Knex, delete