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

Sql Pass Through
Sql Pass ThroughSql Pass Through
Sql Pass Through
jrhampt
 
Nko workshop - node js & nosql
Nko workshop - node js & nosqlNko workshop - node js & nosql
Nko workshop - node js & nosql
Simon Su
 

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

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

Recently uploaded (20)

50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
Keeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security ServicesKeeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security Services
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resources
 

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' }, }, }, })