Relationships (Database Relations)
Relationships: روابط در دیتابیس 🔗
Relationships برای ارتباط بین tables/collections استفاده میشن!
Mongoose Relationships:
// User Schema
const userSchema = new mongoose.Schema({
name: String,
email: String
});
// Post Schema با reference به User
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);
// استفاده با populate
const post = await Post.findById(postId).populate('author');
console.log(post.author.name);
Sequelize Relationships:
// User Model
const User = sequelize.define('User', {
name: DataTypes.STRING,
email: DataTypes.STRING
});
// Post Model
const Post = sequelize.define('Post', {
title: DataTypes.STRING,
content: DataTypes.TEXT
});
// Relationship
User.hasMany(Post);
Post.belongsTo(User);
// استفاده
const user = await User.findByPk(userId, {
include: Post
});
✅ یاد گرفتید: Relationships برای ساختار داده ضروریه!
آماده رفتن به درس بعدی هستید؟
این درس را به پایان رساندید و میتوانید به درس بعدی بروید.