Facebook Pixel

Why avoid $where in MongoDB queries?

$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.

Verify This Answer

Cross-check this information using these trusted sources:

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?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.