// SQL
SELECT * FROM users;
// Knex.js
knex('users')
// SQL
SELECT * FROM users;
// Knex.js
knex('users')
knex('users').select()
// SQL
SELECT * FROM users WHERE name = 'Elana';
// Knex.js
knex('users').where('name', 'Elana')
// SQL
INSERT INTO cities (name) VALUES ('Denver');
// Knex.js
knex('cities').insert({name: 'Denver'})
// SQL
UPDATE cities SET name = 'Chicago' where id = 1;
// Knex.js
knex('cities').where('id', 1).update({ name: 'Chicago'})
// SQL
DELETE FROM cities WHERE id = 1;
// Knex.js
knex('cities').where('id', 1).del()
knex('cities')
.where('id', 1)
.first()
.then(city => {
console.log(city)
})
Make sure you choose the correct RDBMS (PostgreSQL) for code examples because there are some variations.
$ npm init // create package.json
$ npm i -S express pg knex // install pg, knex and express locally
$ npm i knex -g // install knex cli globally
$ knex init // create knexfile.js
* pg is a client that connects Knex to PostgreSQL
module.exports = {
development: {
client: 'pg',
connection: 'postgres://localhost/mydb'
},
production: {
client: 'pg',
connection: process.env.DATABASE_URL
}
}
var environment = process.env.NODE_ENV || 'development'
var config = require('../knexfile.js')[environment]
module.exports = require('knex')(config)