Best practices
A few habits keep Node.js and MongoDB apps fast, safe and maintainable.
In this page:
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
// 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
- Trusting request bodies as queries
- Fetching whole collections
- 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: