دوره‌ها / Node.js / MongoDB با Mongoose (MongoDB & Mongoose)

MongoDB با Mongoose (MongoDB & Mongoose)

15 دقیقه Article

MongoDB با Mongoose: کار با دیتابیس NoSQL 🗄️

Mongoose یک ODM (Object Document Mapper) برای MongoDB است. این کار رو خیلی ساده‌تر میکنه!

نصب و اتصال:

// نصب
// npm install mongoose

const mongoose = require('mongoose');

// اتصال به MongoDB
mongoose.connect('mongodb://localhost:27017/mydb', {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Connection error:', err));

تعریف Schema و Model:

// تعریف Schema
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    age: {
        type: Number,
        min: 0
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
});

// ساخت Model
const User = mongoose.model('User', userSchema);

// استفاده
const user = new User({
    name: 'John',
    email: 'john@example.com',
    age: 30
});

user.save()
    .then(() => console.log('User saved'))
    .catch(err => console.error(err));

CRUD Operations:

// Create
const user = await User.create({ name: 'John', email: 'john@example.com' });

// Read
const users = await User.find();
const user = await User.findById(userId);

// Update
await User.findByIdAndUpdate(userId, { name: 'Jane' });

// Delete
await User.findByIdAndDelete(userId);
✅ یاد گرفتید: Mongoose برای کار با MongoDB عالیه!

آماده رفتن به درس بعدی هستید؟

این درس را به پایان رساندید و می‌توانید به درس بعدی بروید.

برای ذخیره پیشرفت وارد شوید