Το Sequelize είναι ένα ORM βασισμένο σε promises για το Node.js που υποστηρίζει Postgres, MySQL, MariaDB, SQLite και SQL Server.
Σύνδεση & Ορισμός Μοντέλου
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('postgres://user:pass@localhost:5432/mydb');
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
unique: true,
validate: { isEmail: true }
}
});
// Συγχρονισμός σχήματος βάσης δεδομένων
await sequelize.sync();
Λειτουργίες CRUD
// Δημιουργία (Create)
const user = await User.create({ name: 'Alice', email: '[email protected]' });
// Ανάγνωση (Read)
const users = await User.findAll({
where: { name: 'Alice' },
order: [['createdAt', 'DESC']],
limit: 10
});
// Ενημέρωση (Update)
await User.update({ name: 'Bob' }, { where: { id: 1 } });
// Διαγραφή (Delete)
await User.destroy({ where: { id: 1 } });
Συσχετίσεις Μοντέλων
User.hasMany(Post);
Post.belongsTo(User);
// Eager loading με include
const userWithPosts = await User.findOne({
where: { id: 1 },
include: [Post]
});