http://knexjs.org/

Getting started with Knex.js

Rachel Emmer
The Startup
Published in
3 min readJun 4, 2020

--

Note: Before getting started with Knex, you may want to familiarize yourself with the steps necessary to create a basic Express app, as the following information builds on those concepts. Check out my other blog post here to learn how to get started with Node, Express, and Objection.

Knex self describes as “a ‘batteries included’ SQL query builder for Postgres, MSSQL, MySQL, MariaDB, SQLite3, Oracle, and Amazon Redshift designed to be flexible, portable, and fun to use”. Basically, it allows you to write SQL queries in your Node application. This is also where you will create your migrations and your seeds, as well as run queries such as .select, .insert, .update, and .delete.

To get started with Knex.js, run npm install knex followed by npm install database-of-your-choice. The database driver will allow your Express application to interact with your database. Next, you actually need to create the database. This will be done differently depending on what database library you choose. In the case of Postgres, which I use, run createdb database-name in your terminal. Next, you’ll need to initialize a knexfile, by running npx knex init. In the knexfile, you’ll find a development object, which you will change to the following:

development: {  client: “pg”,
connection: “postgres:///database-name
}

Again, this is for PostgresSQL, this will need to be adjusted based on the database you chose.

Back in index.js, include the following code:

const knex = require(“knex”)const config = require(“./knexfile)[process.env.NODE_ENV || “development”]const database = knex(config)

This is requiring in both the Knex package as well as the knexfile that contains our development hash. We can establish our database by passing in config as an argument for knex.

To create our first migration, run npx knex migrate:make table-name. This will make us a migration that we can find in the migrations folder. In here, you’ll see that there are two functions, exports.up and exports.down. If we wanted to create a table for dogs that included their name and age, it would look something like this:

exports.up = function(knex) {
return knex.schema.createTable(“dog”, t => {
t.increments()
t.string(“name”)
t.integer(“age”)
})
}
exports.down = function(knex) {
return knex.schema.dropTableIfExists(“dog”)
}

The exports.up function is what happens going forward (running the migration), whereas the exports.down undos that migration (like a rollback). You’ll notice the exports.up function takes in two arguments, the name of the table and the callback function. Also worth noting, we don’t get auto incrementing IDs for free with Knex, so we must include t.increments. To migrate, run npx knex migrate:latest. To undo, run npx knex migrate:rollback.

Lastly, we want to create a seed file. One of the benefits of Knex is that we can have multiple seed files, which will be organized alphabetically by default. Run npx knex seed:name-of-seed-file. You’ll notice this creates a seed file where we will find the exports.seed function. Here you can enter your seed data. Remember to never seed your data with IDs! T.increments took care of that for us.

That is all the code necessary to create a basic Knex application. If we’d like to write a simple get request to see all of our dogs, we would write the following code in our index.js:

app.get(“/dog”, (request, response) => {
database(“dog”).select()
.then(dogs => {
response.json({dogs})
})
})

Other things you can do with Knex besides .select include .insert, .update, and .delete. And just like that, you have a functioning Knex application!

Resources:

http://knexjs.org/
https://devhints.io/knex

--

--