This Express app uses Knex to create a 'users' table in an in-memory SQLite database. It inserts two users and provides a GET endpoint to fetch all users. Knex builds the SQL queries behind the scenes.
Knex supports many databases like SQLite, PostgreSQL, MySQL, and more.
Always handle errors when running queries in real apps.
Knex queries return promises, so use async/await or .then() to get results.
Summary
Knex lets you write database queries in JavaScript instead of SQL.
It helps keep your code clean, safe, and easy to read.
You can use it with many databases and chain query methods for clarity.
Practice
(1/5)
1. What is the main advantage of using Knex as a query builder in an Express app?
easy
A. It allows writing database queries using JavaScript instead of raw SQL.
B. It automatically creates database tables without any code.
C. It replaces Express middleware for handling requests.
D. It compiles JavaScript into SQL code for faster execution.
Solution
Step 1: Understand Knex's purpose
Knex is designed to let developers write database queries in JavaScript instead of SQL.
Step 2: Compare options
Options B, C, and D describe features Knex does not provide. It does not create tables automatically, replace Express middleware, or compile JS into SQL.
Final Answer:
It allows writing database queries using JavaScript instead of raw SQL. -> Option A
Quick Check:
Knex = JS query builder [OK]
Hint: Knex lets you write queries in JS, not raw SQL [OK]
Common Mistakes:
Thinking Knex creates tables automatically
Confusing Knex with Express middleware
Believing Knex compiles JS to SQL code
2. Which of the following is the correct way to select all rows from a table named users using Knex?
easy
A. knex.tables('users').select('*')
B. knex.from('users').selects()
C. knex.query('SELECT * FROM users')
D. knex.select('*').from('users')
Solution
Step 1: Review Knex select syntax
The common pattern is knex.select('*').from('tableName') to get all rows.
Step 2: Check each option
knex.select('*').from('users') matches the correct syntax. knex.from('users').selects() uses invalid selects() method. knex.tables('users').select('*') uses knex.tables which is not standard Knex syntax. knex.query('SELECT * FROM users') uses raw SQL string which is not the Knex query builder method.