DEV Community

Cover image for Crud In NodeJs
Bibek Dhami
Bibek Dhami

Posted on • Edited on • Originally published at bvek.hashnode.dev

Crud In NodeJs

Mysql With Knexjs In Node

Introduction

In this section, we will learn how to set up and perform crud with knex.js in nodejs and I will be using
Postman to test routes.

Project Structure

directorytree.PNG
STEP
1- Getting ready express framework

npm install express
npm install body-parser
Enter fullscreen mode Exit fullscreen mode

Then create an app.js file
As we will be keeping our route in a separate directory import the directory with a file using the app. use(require("./routes/router")). In app.js file will only start the express server.

app.png

Now in the router.js file set body-parser-urlencoded({extended: true}) uses express.json() to parse the JSON data which we will be sending through postman.

Define all your routes here and import related functions in respective routes.

router.png
2- Installation

npm install knex

 npm install mysql
Enter fullscreen mode Exit fullscreen mode

3-Initialize Knex

npm knex init
Enter fullscreen mode Exit fullscreen mode

4- Creating Migration File

knex migrate: make tbl_person
knex migrate: make tbl_favourite
Enter fullscreen mode Exit fullscreen mode

Define Schema in the migration file. Migration file requires two functions up and down. Up function is run when creating a table in the database whereas the down function is run when rolling back migration.

tbl_person.png

tbl_fav.png

5-Writing knex Query

Insert Person

For inserting, I will be using the async arrow function. Store all the request body in an object along with the key that matches the field of the respective table and pass the object in knex query. Which knex will map it into raw SQL query under the hood.

addPerson.png
Testing insert api with postman
postPerson.PNG

*Patch Person *

For updating store the body data into object and params in a variable. To pass it into knex query as:
patchPerson.png
Testing Patch API
patchPerson.PNG

*Get Person *

For selecting person knex orm query is as:
getPerson.png
testing get person API
getPerson.PNG

Add Favourite

knex query for adding favourite

personIdFav.png
testing add Favourite API
postFavourite.PNG

*Left Join *

Left join select the matching data between the left table and right table and all the records from the left table.
getFavJoin.png
testing left join route with the postman
getFavouriteLeftJoin.PNG

.env Configuration used in project
Make the necessary needed change and to able to use .env file install

npm install dotenv
Enter fullscreen mode Exit fullscreen mode

env.PNG

SourceCode

Bonus

Knex Cheatsheet

KnexQuery to raw query

Top comments (0)