← Back to MongoDB Course | Chapter 10: MongoDB with Node.js | Lesson 7 of 7

बेहतरीन Practices

कुछ habits Node.js और MongoDB apps को fast, safe, और maintainable रखती हैं।

In this page:

  1. Best Practices

Best Practices

एक single connection reuse करें, अपनी query fields index करें, work limit करने के लिए projection और lean इस्तेमाल करें, बड़े results paginate करें, database तक पहुँचने से पहले input validate करें, कभी भी raw user input से queries न बनाएँ (NoSQL injection से बचें), credentials environment variables में रखें, और slow queries monitor करें।

Note: कभी req.body सीधे एक query में pass न करें; fields pick और validate करें।

उदाहरण: Best practices

javascript
// Bad: attacker can send { "email": { "$ne": null } } and match any user
// const user = await User.findOne(req.body);

// Good: pick fields and coerce types
const email = String(req.body.email || "");
const user = await User.findOne({ email }).select("name email").lean();
const page = Math.max(1, Number(req.query.page) || 1);
const list = await User.find().sort({ _id: 1 }).skip((page - 1) * 20).limit(20).lean();

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. request bodies को queries की तरह trust करना
  2. पूरी collections fetch करना
  3. connection strings hard-code करना
चैप्टर सारांश
  • एक connection reuse करें
  • Index और project करें
  • Results paginate करें
  • NoSQL injection रोकें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.