Catalog / Knex.js Cheat Sheet
Knex.js Cheat Sheet
A comprehensive cheat sheet for Knex.js, a SQL query builder for Node.js, covering database connections, schema building, querying, migrations, and seeding.
Getting Started & Connections
Installation
Install Knex.js via npm or yarn:
|
Also, install the database driver for your database (e.g., pg for PostgreSQL, mysql for MySQL, sqlite3 for SQLite):
|
Initializing Knex
After setting up the connection, you can use the |
|
Database Connections
PostgreSQL |
|
MySQL |
|
SQLite3 |
|
MSSQL |
|
Connection String |
|
Schema Builder
Creating Tables
|
Column Types
|
Auto-incrementing primary key. |
|
String column with optional length. |
|
Integer column. |
|
Boolean column. |
|
Date column. |
|
Datetime column. |
|
Timestamp column. |
|
JSON column. |
|
JSONB column. |
Constraints
|
Adds a unique constraint to the specified column(s). |
|
Sets the specified column(s) as the primary key. |
|
Adds a foreign key constraint. |
Query Builder
Basic Queries
Selecting data:
|
Inserting data:
|
Updating data:
|
Deleting data:
|
Where Clauses
|
Basic where clause. |
|
Where clause with operator (e.g., ‘=’, ‘>’, ‘<’). |
|
Where clause with an object for multiple conditions. |
|
Where column’s value is in the array. |
|
Where column’s value is null. |
|
Where column’s value is between value1 and value2. |
Joins
|
Other join types:
|
Migrations & Seedings
Migrations Setup
Initialize Knex migrations:
|
This command creates a |
Migration Commands
|
Creates a new migration file. |
|
Runs all pending migrations. |
|
Rolls back the latest migration batch. |
|
Shows the current migration status. |
Seedings
Create seed file:
|
Run seed file:
|
Example Seed File:
|