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

Best practices

A few habits keep Node.js and MongoDB apps fast, safe and maintainable.

In this page:

  1. Best practices

Best practices

Reuse a single connection, index your query fields, use projection and lean to limit work, paginate large results, validate input before it reaches the database, never build queries from raw user input (avoid NoSQL injection), keep credentials in environment variables and monitor slow queries.

Note: Never pass req.body directly into a query; pick and validate the fields.

Example: 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
  1. Trusting request bodies as queries
  2. Fetching whole collections
  3. Hard-coding connection strings
Chapter Summary
  • Reuse one connection
  • Index and project
  • Paginate results
  • Prevent 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.