Simple CRUD Operations with Sequelize ORM
Simple CRUD Operations with Sequelize ORM
Introduction: What is Sequelize ORM?
Modern web applications mostly interact with databases, and ORM (Object-Relational Mapping) tools are used to facilitate this communication. Sequelize ORM is a popular and powerful ORM library used in the Node.js environment. It allows you to easily perform database operations without writing SQL queries. In this article, under the title "Simple CRUD Operations with Sequelize ORM," we will proceed with examples to demonstrate how to perform basic CRUD (Create, Read, Update, Delete) operations.
Creating a Model and Connection with Sequelize
To implement the topic "Simple CRUD Operations with Sequelize ORM," you first need to add Sequelize and the relevant database driver to your project. For a PostgreSQL project, for example, you can use the following command:
npm install sequelize pg pg-hstore
Then, to create a model, you can follow these steps:
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'localhost',
dialect: 'postgres'
});
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false
}
});
sequelize.sync();
CRUD Operations: Create, Read, Update, Delete
Adding a Record (Create)
async function addNewUser() {
const newUser = await User.create({ name: 'Ali Veli', email: 'ali@veli.com' });
console.log(newUser.toJSON());
}
addNewUser();
Reading a Record (Read)
async function getUsers() {
const users = await User.findAll();
console.log(users.map(u => u.toJSON()));
}
getUsers();
Updating a Record (Update)
async function updateUser(id, newName) {
await User.update({ name: newName }, { where: { id } });
console.log('User updated.');
}
updateUser(1, 'Veli Ali');
Deleting a Record (Delete)
async function deleteUser(id) {
await User.destroy({ where: { id } });
console.log('User deleted.');
}
deleteUser(1);
Conclusion and Tips
Under the title "Simple CRUD Operations with Sequelize ORM," we have learned, with examples, one of the best ways to quickly and securely implement database functions in a Node.js project. With Sequelize, you can keep your code simple, secure, and easy to maintain, performing all essential operations comfortably without needing complex SQL queries. For detailed information and advanced usage examples, we recommend checking out the official Sequelize documentation.

Yorum Gönder