SlideShare a Scribd company logo
Switch to Backend
Pratik Majumdar
@codadept
MongoDB & Prisma
Recap
Today’s Agenda
Database Prisma
ORM vs ODM Error Handling
SQL vs NoSQL
MongoDB
CRUD
● Systematic/organized collection of data
● Easily accessible and manageable
● SQL vs NoSQL
Database
MS Excel?
• SQL
○ Relational Database
○ Rows and columns
○ Pre-defined schema
○ Eg. MySQL, PostgreSQL
SQL vs NoSQL
Schema vs Schema-less
• NoSQL
○ Non-Relational Database
○ Documents
○ Dynamic schema
○ Eg. MongoDB, Redis
SELECT * FROM classroom WHERE id=1;
Need for ORM/ODM?
MySQL
MongoDB
db.classroom.find({id: 1})
SELECT
C.CUSTOMER_NAME, C.CITY, C.GRADE,
S.NAME AS "SALESMAN",
O.ORDER_NO, O.ORDER_DATE,
O.PURCHASE_AMT
FROM CUSTOMER C
RIGHT JOIN SALESMAN S
ON S.SALESMAN_ID = C.SALESMAN_ID
LEFT JOIN ORDERS O
ON O.CUSTOMER_ID = C.CUSTOMER_ID
WHERE
O.PURCHASE_AMT >= 2000
AND
C.GRADE IS NOT NULL;
More complex query
We don’t write SQL or MongoDB Query Language in our project to access DB.
We use such mappers
ORM
● Object Relational Mapping
● Perform CRUD in Relational DB
ODM
● Object Document Mapping
● Perform CRUD in Non-Relational DB
ORM vs ODM
JS <-> Mapper <-> DB
● Dynamic schema
● Here instead of tables as in SQL DBs we have collections
MongoDB
NoSQL Database
user
{
“username”:
“codadept”,
“scholarId”:
2012005
}
user
{
“firstName”:
“Pratik”,
“scholarId”:
2012005
}
Stores data in
BSON - Binary Encoded JSON
MongoDB
Datatype
Has more data types than JSON
JSON
String, Boolean, Number,
Array, Object, null
BSON
String, Boolean, Number
(Integer, Float, Long,
Decimal128...), Array, null,
Date, BinData
MongoDB
ObjectId
Each document in the collection has _id field which acts as the unique
identifier for that document.
MongoDB
Query using the mongodb CLI
using my_database;
db.createCollection(“user”)
db.user.insert({“id”: 1, “name”:
“Pratik”, “username”: “codadept”})
db.user.find()
Prisma
ORM/ODM
Prisma is a auto-generated query-builder for Node.js
Can be used both as ORM or ODM based on the database we use
Other alternatives
For SQL - sequelize
For MongoDB - mongoose
Prisma
Why?
● Think as objects and classes instead of complex queries
● Type-safe and auto-completion
● Easy to change databases
Prisma
Schema file prisma/schema.prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
posts Post[]
}
Prisma
Components
● Data source: Specifies your database connection (via an
environment variable)
● Generator: Indicates that you want to generate Prisma Client
● Data model: Defines your application models
Prisma
Data model
● Represent a table in relational databases or a collection in
MongoDB
● Provide the foundation for the queries in the Prisma Client API
Prisma
Accessing your DB with @prisma/client
npm install @prisma/client
This invokes the prisma generate command which which reads your
Prisma schema and generates the Prisma Client code.
Prisma
Querying
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// Run inside `async` function
const allUsers = await prisma.user.findMany()
Let’s code
// Run inside `async` function
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Join us for Prisma Day
2020' },
},
},
})
Thank you

More Related Content

Similar to Switch to Backend 2023 | Day 2 Part 1

The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
valuebound
 
Change RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDBChange RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDB
Apaichon Punopas
 
MongoDB Distilled
MongoDB DistilledMongoDB Distilled
MongoDB Distilled
b0ris_1
 
M|18 Analytics as a Service
M|18 Analytics as a ServiceM|18 Analytics as a Service
M|18 Analytics as a Service
MariaDB plc
 
SQL Pass Through and the ODBC Interface
SQL Pass Through and the ODBC InterfaceSQL Pass Through and the ODBC Interface
SQL Pass Through and the ODBC Interface
jrhampt
 
Sql Pass Through
Sql Pass ThroughSql Pass Through
Sql Pass Throughjrhampt
 
MongoDB Schema Design Tips & Tricks
MongoDB Schema Design Tips & TricksMongoDB Schema Design Tips & Tricks
MongoDB Schema Design Tips & Tricks
Juan Antonio Roy Couto
 
Your Database Cannot Do this (well)
Your Database Cannot Do this (well)Your Database Cannot Do this (well)
Your Database Cannot Do this (well)
javier ramirez
 
Spark & Cassandra - DevFest Córdoba
Spark & Cassandra - DevFest CórdobaSpark & Cassandra - DevFest Córdoba
Spark & Cassandra - DevFest Córdoba
Jose Mº Muñoz
 
Teri Grossheim - Amazon Presentation
Teri Grossheim - Amazon PresentationTeri Grossheim - Amazon Presentation
Teri Grossheim - Amazon Presentation
Teri Grossheim
 
Introduction to Spark Datasets - Functional and relational together at last
Introduction to Spark Datasets - Functional and relational together at lastIntroduction to Spark Datasets - Functional and relational together at last
Introduction to Spark Datasets - Functional and relational together at last
Holden Karau
 
Data lineage and observability with Marquez - subsurface 2020
Data lineage and observability with Marquez - subsurface 2020Data lineage and observability with Marquez - subsurface 2020
Data lineage and observability with Marquez - subsurface 2020
Julien Le Dem
 
Postgres-XC as a Key Value Store Compared To MongoDB
Postgres-XC as a Key Value Store Compared To MongoDBPostgres-XC as a Key Value Store Compared To MongoDB
Postgres-XC as a Key Value Store Compared To MongoDB
Mason Sharp
 
Nko workshop - node js & nosql
Nko workshop - node js & nosqlNko workshop - node js & nosql
Nko workshop - node js & nosqlSimon Su
 
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Mydbops
 
SQL Access to NoSQL
SQL Access to NoSQLSQL Access to NoSQL
SQL Access to NoSQL
Progress
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL Databases
Eduard Tudenhoefner
 
MongoDB
MongoDBMongoDB
MongoDB
wiTTyMinds1
 
EC-WEB: Validator and Preview for the JobPosting Data Model of Schema.org
EC-WEB: Validator and Preview for the JobPosting Data Model of Schema.orgEC-WEB: Validator and Preview for the JobPosting Data Model of Schema.org
EC-WEB: Validator and Preview for the JobPosting Data Model of Schema.org
Jindřich Mynarz
 

Similar to Switch to Backend 2023 | Day 2 Part 1 (20)

The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 
Change RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDBChange RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDB
 
MongoDB Distilled
MongoDB DistilledMongoDB Distilled
MongoDB Distilled
 
M|18 Analytics as a Service
M|18 Analytics as a ServiceM|18 Analytics as a Service
M|18 Analytics as a Service
 
SQL Pass Through and the ODBC Interface
SQL Pass Through and the ODBC InterfaceSQL Pass Through and the ODBC Interface
SQL Pass Through and the ODBC Interface
 
Sql Pass Through
Sql Pass ThroughSql Pass Through
Sql Pass Through
 
MongoDB Schema Design Tips & Tricks
MongoDB Schema Design Tips & TricksMongoDB Schema Design Tips & Tricks
MongoDB Schema Design Tips & Tricks
 
Your Database Cannot Do this (well)
Your Database Cannot Do this (well)Your Database Cannot Do this (well)
Your Database Cannot Do this (well)
 
MongoDB DOC v1.5
MongoDB DOC v1.5MongoDB DOC v1.5
MongoDB DOC v1.5
 
Spark & Cassandra - DevFest Córdoba
Spark & Cassandra - DevFest CórdobaSpark & Cassandra - DevFest Córdoba
Spark & Cassandra - DevFest Córdoba
 
Teri Grossheim - Amazon Presentation
Teri Grossheim - Amazon PresentationTeri Grossheim - Amazon Presentation
Teri Grossheim - Amazon Presentation
 
Introduction to Spark Datasets - Functional and relational together at last
Introduction to Spark Datasets - Functional and relational together at lastIntroduction to Spark Datasets - Functional and relational together at last
Introduction to Spark Datasets - Functional and relational together at last
 
Data lineage and observability with Marquez - subsurface 2020
Data lineage and observability with Marquez - subsurface 2020Data lineage and observability with Marquez - subsurface 2020
Data lineage and observability with Marquez - subsurface 2020
 
Postgres-XC as a Key Value Store Compared To MongoDB
Postgres-XC as a Key Value Store Compared To MongoDBPostgres-XC as a Key Value Store Compared To MongoDB
Postgres-XC as a Key Value Store Compared To MongoDB
 
Nko workshop - node js & nosql
Nko workshop - node js & nosqlNko workshop - node js & nosql
Nko workshop - node js & nosql
 
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
Use Performance Insights To Enhance MongoDB Performance - (Manosh Malai - Myd...
 
SQL Access to NoSQL
SQL Access to NoSQLSQL Access to NoSQL
SQL Access to NoSQL
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL Databases
 
MongoDB
MongoDBMongoDB
MongoDB
 
EC-WEB: Validator and Preview for the JobPosting Data Model of Schema.org
EC-WEB: Validator and Preview for the JobPosting Data Model of Schema.orgEC-WEB: Validator and Preview for the JobPosting Data Model of Schema.org
EC-WEB: Validator and Preview for the JobPosting Data Model of Schema.org
 

More from Google Developer Students Club NIT Silchar

Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKitSwitch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
Google Developer Students Club NIT Silchar
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023 | Day 1 Part 2
Switch to Backend 2023 | Day 1 Part 2Switch to Backend 2023 | Day 1 Part 2
Switch to Backend 2023 | Day 1 Part 2
Google Developer Students Club NIT Silchar
 
Switch to Backend 2023 | Day 1 Part 1
Switch to Backend 2023 | Day 1 Part 1Switch to Backend 2023 | Day 1 Part 1
Switch to Backend 2023 | Day 1 Part 1
Google Developer Students Club NIT Silchar
 
Flutter Festival - Intro Session
Flutter Festival - Intro SessionFlutter Festival - Intro Session
Flutter Festival - Intro Session
Google Developer Students Club NIT Silchar
 
Roadmap to Development
Roadmap to DevelopmentRoadmap to Development
Android Study Jams - Info Session
Android Study Jams - Info SessionAndroid Study Jams - Info Session
Android Study Jams - Info Session
Google Developer Students Club NIT Silchar
 
30 days of cloud: Info session
30 days of cloud: Info session30 days of cloud: Info session
30 days of cloud: Info session
Google Developer Students Club NIT Silchar
 
Flutter Bootcamp
Flutter BootcampFlutter Bootcamp
Intro to Git & GitHub
Intro to Git & GitHubIntro to Git & GitHub

More from Google Developer Students Club NIT Silchar (10)

Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKitSwitch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
Switch to Svelte | GDSC NIT Silchar | Speaker Session | SvelteKit
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Switch to Backend 2023 | Day 1 Part 2
Switch to Backend 2023 | Day 1 Part 2Switch to Backend 2023 | Day 1 Part 2
Switch to Backend 2023 | Day 1 Part 2
 
Switch to Backend 2023 | Day 1 Part 1
Switch to Backend 2023 | Day 1 Part 1Switch to Backend 2023 | Day 1 Part 1
Switch to Backend 2023 | Day 1 Part 1
 
Flutter Festival - Intro Session
Flutter Festival - Intro SessionFlutter Festival - Intro Session
Flutter Festival - Intro Session
 
Roadmap to Development
Roadmap to DevelopmentRoadmap to Development
Roadmap to Development
 
Android Study Jams - Info Session
Android Study Jams - Info SessionAndroid Study Jams - Info Session
Android Study Jams - Info Session
 
30 days of cloud: Info session
30 days of cloud: Info session30 days of cloud: Info session
30 days of cloud: Info session
 
Flutter Bootcamp
Flutter BootcampFlutter Bootcamp
Flutter Bootcamp
 
Intro to Git & GitHub
Intro to Git & GitHubIntro to Git & GitHub
Intro to Git & GitHub
 

Recently uploaded

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 

Switch to Backend 2023 | Day 2 Part 1

  • 1. Switch to Backend Pratik Majumdar @codadept MongoDB & Prisma
  • 3. Today’s Agenda Database Prisma ORM vs ODM Error Handling SQL vs NoSQL MongoDB CRUD
  • 4. ● Systematic/organized collection of data ● Easily accessible and manageable ● SQL vs NoSQL Database MS Excel?
  • 5. • SQL ○ Relational Database ○ Rows and columns ○ Pre-defined schema ○ Eg. MySQL, PostgreSQL SQL vs NoSQL Schema vs Schema-less • NoSQL ○ Non-Relational Database ○ Documents ○ Dynamic schema ○ Eg. MongoDB, Redis
  • 6. SELECT * FROM classroom WHERE id=1; Need for ORM/ODM? MySQL MongoDB db.classroom.find({id: 1})
  • 7. SELECT C.CUSTOMER_NAME, C.CITY, C.GRADE, S.NAME AS "SALESMAN", O.ORDER_NO, O.ORDER_DATE, O.PURCHASE_AMT FROM CUSTOMER C RIGHT JOIN SALESMAN S ON S.SALESMAN_ID = C.SALESMAN_ID LEFT JOIN ORDERS O ON O.CUSTOMER_ID = C.CUSTOMER_ID WHERE O.PURCHASE_AMT >= 2000 AND C.GRADE IS NOT NULL; More complex query
  • 8. We don’t write SQL or MongoDB Query Language in our project to access DB. We use such mappers ORM ● Object Relational Mapping ● Perform CRUD in Relational DB ODM ● Object Document Mapping ● Perform CRUD in Non-Relational DB ORM vs ODM JS <-> Mapper <-> DB
  • 9. ● Dynamic schema ● Here instead of tables as in SQL DBs we have collections MongoDB NoSQL Database user { “username”: “codadept”, “scholarId”: 2012005 } user { “firstName”: “Pratik”, “scholarId”: 2012005 }
  • 10. Stores data in BSON - Binary Encoded JSON MongoDB Datatype Has more data types than JSON JSON String, Boolean, Number, Array, Object, null BSON String, Boolean, Number (Integer, Float, Long, Decimal128...), Array, null, Date, BinData
  • 11. MongoDB ObjectId Each document in the collection has _id field which acts as the unique identifier for that document.
  • 12. MongoDB Query using the mongodb CLI using my_database; db.createCollection(“user”) db.user.insert({“id”: 1, “name”: “Pratik”, “username”: “codadept”}) db.user.find()
  • 13. Prisma ORM/ODM Prisma is a auto-generated query-builder for Node.js Can be used both as ORM or ODM based on the database we use Other alternatives For SQL - sequelize For MongoDB - mongoose
  • 14. Prisma Why? ● Think as objects and classes instead of complex queries ● Type-safe and auto-completion ● Easy to change databases
  • 15. Prisma Schema file prisma/schema.prisma datasource db { provider = "mongodb" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } model Post { id String @id @default(auto()) @map("_id") @db.ObjectId title String content String? published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId String @db.ObjectId } model User { id String @id @default(auto()) @map("_id") @db.ObjectId email String @unique name String? posts Post[] }
  • 16. Prisma Components ● Data source: Specifies your database connection (via an environment variable) ● Generator: Indicates that you want to generate Prisma Client ● Data model: Defines your application models
  • 17. Prisma Data model ● Represent a table in relational databases or a collection in MongoDB ● Provide the foundation for the queries in the Prisma Client API
  • 18. Prisma Accessing your DB with @prisma/client npm install @prisma/client This invokes the prisma generate command which which reads your Prisma schema and generates the Prisma Client code.
  • 19. Prisma Querying import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() // Run inside `async` function const allUsers = await prisma.user.findMany()
  • 20. Let’s code // Run inside `async` function const user = await prisma.user.create({ data: { name: 'Alice', email: 'alice@prisma.io', posts: { create: { title: 'Join us for Prisma Day 2020' }, }, }, })