$where accepts JavaScript and is a common injection vector. An attacker can run arbitrary JavaScript inside the database. Avoid it; if you must use it, sanitize the input strictly. There is almost always a better way to write the query.
Why avoid $where in MongoDB queries?
More FAQs in How to Prevent NoSQL Injection in MongoDB
When you build a MongoDB query from user input without sanitization, a user can send operators like $gt, $ne, $or to manipulate the query. Example: { email: { $gt: '' }, password: { $gt: '' } } bypasses login by matching the first user.
Use express-mongo-sanitize (strips $ and .), validate with Zod (enforces types), use Mongoose (casts based on schema), cast inputs explicitly with String(), avoid $where, and whitelist filter fields. Layer defenses.
Strips $ and . from req.body, req.params, and req.query. A payload of { email: { $gt: '' } } becomes { email: 'gt' }, which fails the query. Add it after express.json so all bodies are sanitized.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.