0Pricing
MongoDB Academy · درس

استعلامات Mongoose وتسلسلها والمستندات الرشيقة

سيسلسل المتعلمون مساعدات استعلام Mongoose، ويستخدمون .lean() لأداء الكائنات الخام POJO، ويقارنون واجهة الاستعلام ببرنامج التشغيل الأصلي.

استعلامات Mongoose وتسلسلها والمستندات الرشيقة درس مجاني في MongoDB Academy على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في MongoDB Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة MongoDB Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Mongoose Query Objects

When you call a Mongoose query method like User.find(), it returns a Query object rather than a Promise. This Query object is lazy—it does not execute until you explicitly call it with .then(), await, or .exec(). Before execution, you can chain additional query modifiers to build up the complete query. This chainable API is one of Mongoose's most ergonomic features.

const User = require('./models/user');

// This does NOT execute immediately — returns a Query object
const query = User.find({ active: true });

// Now execute it with await
const users = await query;

// Or chain modifiers before executing:
const result = await User.find({ active: true })
  .sort({ createdAt: -1 })
  .limit(10)
  .select('name email -_id');
  // select() projects fields: '+field' includes, '-field' excludes

Chaining Query Modifiers

Mongoose query modifiers like .sort(), .limit(), .skip(), .select(), and .populate() can be chained in any order before execution. The underlying Query object accumulates all modifiers and sends a single optimized query to MongoDB. This is functionally equivalent to passing options to the native driver's find(filter, options) but reads more naturally as a fluent builder.

const orders = await Order
  .find({ status: 'completed', userId: currentUserId })
  .sort({ createdAt: -1 })              // newest first
  .skip(page * pageSize)                // pagination offset
  .limit(pageSize)                      // page size
  .select('_id total status createdAt') // projection
  .lean();                              // return plain objects (discussed next)

console.log('Orders on this page:', orders.length);

The .lean() Method: Raw POJO Performance

By default, Mongoose wraps every document returned by a query in a Mongoose Document instance—a heavy object with change tracking, methods, virtuals, and middleware hooks. The .lean() method tells Mongoose to return plain JavaScript objects (POJOs) instead. Lean queries are typically 2-5x faster and use less memory because Mongoose skips the Document wrapping. Use .lean() for read-only operations where you don't need document methods or save/update hooks.

// Without .lean() — heavy Mongoose Document objects
const docsWithMethods = await User.find({ active: true });
// docsWithMethods[0].save() works, but incurs overhead

// With .lean() — plain JavaScript objects, much faster
const pureObjects = await User.find({ active: true }).lean();
// pureObjects[0].save() does NOT work — it's a plain object
// But JSON.stringify, spread operators, and array methods are all faster

console.log(typeof docsWithMethods[0].save); // 'function'
console.log(typeof pureObjects[0].save);     // 'undefined'

When to Use .lean() vs Full Documents

Use .lean() when: you are only reading data (GET endpoints), you need to serialize to JSON quickly, or you are processing many documents in bulk. Do not use .lean() when: you need to call .save() on the result, use virtual properties, run document middleware, or access instance methods. A good rule of thumb: API reads → lean, mutation flows → full Mongoose documents.

// API read endpoint — use .lean() for speed
router.get('/products', async (req, res) => {
  const products = await Product.find({}).lean(); // fastest, no doc wrapper
  res.json(products);
});

// Update endpoint — use full Mongoose document to access instance methods
router.post('/users/:id/deactivate', async (req, res) => {
  const user = await User.findById(req.params.id); // full document, NO .lean()
  await user.sendDeactivationEmail(); // instance method won't work with .lean()
  user.active = false;
  await user.save(); // document method won't work with .lean()
  res.json({ success: true });
});

findById and findOne Convenience Methods

Mongoose adds convenience query methods not available in the native driver. Model.findById(id) is equivalent to Model.findOne({ _id: id }) and automatically converts string IDs to ObjectId. Model.findByIdAndUpdate(id, update, options) and Model.findByIdAndDelete(id) combine lookup and modification in a single atomic operation. These methods greatly reduce boilerplate in CRUD route handlers.

// findById — automatic ObjectId conversion from string
const user = await User.findById('64a1b2c3d4e5f6789012345a').lean();

// findByIdAndUpdate — find, update, and return result atomically
const updatedProduct = await Product.findByIdAndUpdate(
  productId,
  { $set: { price: 199.99 }, $inc: { updateCount: 1 } },
  { new: true, runValidators: true }  // return new doc, run validators
);

// findByIdAndDelete — find and delete atomically
const deletedUser = await User.findByIdAndDelete(userId);
console.log('Deleted:', deletedUser ? deletedUser.email : 'not found');

Counting Documents

Mongoose provides efficient document counting methods. Model.countDocuments(filter) applies a filter and counts matching documents—it scans matching documents and uses indexes. Model.estimatedDocumentCount() uses collection metadata for an approximate but instantaneous count without a filter—useful for dashboard totals on large collections where exact counts are not critical.

// Exact count with filter — uses an index if available
const activeUsers = await User.countDocuments({ active: true, role: 'user' });
console.log('Active users:', activeUsers);

// Fast approximate count — no filter, uses collection stats
const totalProducts = await Product.estimatedDocumentCount();
console.log('Approximate total products:', totalProducts);

// In Express pagination:
const [data, total] = await Promise.all([
  User.find({}).skip(offset).limit(pageSize).lean(),
  User.countDocuments({})
]);
res.json({ data, total, pages: Math.ceil(total / pageSize) });

Populate: Resolving References

.populate() is one of Mongoose's most powerful features—it replaces an ObjectId reference field with the actual referenced document, fetched from another collection. Under the hood, Mongoose issues a second query to the referenced collection and substitutes the IDs. It is equivalent to $lookup in the aggregation pipeline but with a simpler API.

const Order = mongoose.model('Order', new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  productIds: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Product' }]
}));

// Populate the userId reference with the full User document
const order = await Order
  .findById(orderId)
  .populate('userId', 'name email')    // only select name and email from User
  .populate('productIds', 'name price') // populate array of references
  .lean();

console.log(order.userId.email);      // 'alice@example.com'
console.log(order.productIds[0].name); // 'Laptop'

Mongoose vs Native Driver: When to Choose

Mongoose adds validation, populate, middleware, and a convenient query API—at the cost of some overhead. Choose Mongoose when: your application has well-defined, stable schemas; you want schema validation without JSON Schema validators; you need populate for reference resolution; or you are building a conventional REST API. Choose the native driver when: you need maximum performance, are working with dynamic schemas, are building aggregation-heavy analytics, or are writing a microservice with minimal dependencies.

// Mongoose: ergonomic, validates, populate works
const user = await User.findOne({ email }).select('-password').populate('profile');

// Native driver: faster, raw, no middleware
const user = await db.collection('users')
  .findOne({ email }, { projection: { password: 0 } });

exec() and Error Handling

Calling .exec() explicitly converts a Mongoose Query to a Promise and is the traditional way to execute queries when using .catch() promise chaining. With async/await, you can omit .exec()—a bare await User.find({}) works fine. However, some developers prefer .exec() for clarity or when building query objects programmatically. Both patterns produce identical results.

// With .exec() — explicit Promise conversion
const user = await User.findOne({ email }).exec();

// Without .exec() — implicit execution via await
const user = await User.findOne({ email });

// Error handling with try/catch (both forms work the same)
try {
  const user = await User.findById(id);
  if (!user) throw new Error('User not found');
} catch (err) {
  if (err.name === 'CastError') {
    res.status(400).json({ error: 'Invalid ID format' });
  } else {
    res.status(500).json({ error: err.message });
  }
}

Query Builder Pattern

Because Mongoose queries are lazy, you can conditionally build queries in separate statements before execution. This is useful when query parameters are optional—add sort or filters only when the parameter is present. This pattern is much cleaner than constructing dynamic query strings and keeps the code readable.

async function searchProducts(filters) {
  let query = Product.find();

  if (filters.category) {
    query = query.where('category').equals(filters.category);
  }
  if (filters.maxPrice) {
    query = query.where('price').lte(filters.maxPrice);
  }
  if (filters.inStock) {
    query = query.where('stock').gt(0);
  }

  const sortField = filters.sortBy || 'createdAt';
  query = query.sort({ [sortField]: -1 }).limit(50).lean();

  return query; // executes here via await in the caller
}

Aggregate Pipeline in Mongoose

Mongoose models also support the aggregation pipeline via Model.aggregate(pipeline). Unlike regular Mongoose queries, aggregation bypasses schema casting, Mongoose middleware, and populate—it behaves similarly to calling the native driver's aggregate directly. Aggregate returns a plain array of objects, never Mongoose Documents. Use Model.aggregate() for complex analytics and reporting that don't benefit from Mongoose's abstractions.

// Aggregation in Mongoose — bypasses Mongoose middleware and casting
const salesByRegion = await Order.aggregate([
  { $match: { status: 'completed' } },
  {
    $group: {
      _id: '$region',
      totalRevenue: { $sum: '$total' },
      orderCount: { $sum: 1 },
      avgOrder: { $avg: '$total' }
    }
  },
  { $sort: { totalRevenue: -1 } }
]);

// salesByRegion is a plain array — no Mongoose Document wrapper

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: Mongoose query methods return lazy Query objects that can be chained with .sort(), .limit(), .skip(), .select(), and .populate() before execution, .lean() returns plain JavaScript objects for better performance on read-only operations, and Model.aggregate() bypasses Mongoose abstractions and behaves like the native driver for analytics pipelines. Next up we explore Mongoose middleware — pre and post hooks for custom logic around save, find, and other operations.

الأسئلة الشائعة

هل درس «استعلامات Mongoose وتسلسلها والمستندات الرشيقة» مجاني؟

نعم — نص درس «استعلامات Mongoose وتسلسلها والمستندات الرشيقة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة MongoDB Academy، انتقل إلى CoddyKit PRO. تتضمن دورة MongoDB Academy 4 دروس في المجموع.

ماذا ستتعلم في «استعلامات Mongoose وتسلسلها والمستندات الرشيقة»؟

سيسلسل المتعلمون مساعدات استعلام Mongoose، ويستخدمون .lean() لأداء الكائنات الخام POJO، ويقارنون واجهة الاستعلام ببرنامج التشغيل الأصلي. تتمرن على MongoDB Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ MongoDB Academy؟

لا تُشترط خبرة سابقة. MongoDB Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «استعلامات Mongoose وتسلسلها والمستندات الرشيقة»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس MongoDB Academy هذا؟

نعم. كل درس في MongoDB Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. الاتصال باستخدام برنامج تشغيل Node.js الرسمي
  2. مخططات Mongoose ونماذجه وخصائصه الافتراضية
  3. استعلامات Mongoose وتسلسلها والمستندات الرشيقة
  4. البرمجيات الوسيطة في Mongoose: خطافات ما قبل التنفيذ وما بعده
← العودة إلى MongoDB Academy