ORM helps you work with databases using simple code instead of writing complex queries. It makes saving and getting data easier and faster.
0
0
ORM concept (Sequelize, Prisma overview) in Node.js
Introduction
When you want to save user information like names and emails in a database.
When you need to get data from a database without writing SQL queries.
When you want to change database data using JavaScript code.
When you want to keep your database code organized and easy to read.
When you want to switch databases without changing much code.
Syntax
Node.js
const { Model, DataTypes } = require('sequelize');
class User extends Model {}
User.init({
username: DataTypes.STRING,
birthday: DataTypes.DATE
}, { sequelize, modelName: 'user' });This example shows Sequelize syntax to define a model.
Models represent tables in your database.
Examples
This example shows how Prisma fetches all users from the database using JavaScript.
Node.js
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
async function main() {
const allUsers = await prisma.user.findMany();
console.log(allUsers);
}
main();This example shows Sequelize defining a User model with username and birthday fields.
Node.js
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');
const User = sequelize.define('User', {
username: DataTypes.STRING,
birthday: DataTypes.DATE
});Sample Program
This program uses Prisma to add a new user named Alice and then fetches all users from the database. It prints the created user and the list of all users.
Node.js
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); async function main() { // Create a new user const newUser = await prisma.user.create({ data: { username: 'Alice', email: 'alice@example.com' } }); // Fetch all users const users = await prisma.user.findMany(); console.log('Created user:', newUser); console.log('All users:', users); } main() .catch(e => console.error(e)) .finally(async () => { await prisma.$disconnect(); });
OutputSuccess
Important Notes
ORMs like Sequelize and Prisma let you write JavaScript instead of SQL.
They help avoid mistakes by checking your data types.
Prisma uses a special file to define your database models, while Sequelize uses JavaScript code.
Summary
ORMs make database work easier by using code instead of SQL.
Sequelize and Prisma are popular tools for Node.js to handle databases.
They help keep your code clean and simple when working with data.