MongoDB queries built with Mongoose aren’t vulnerable to classic SQL injection because they’re not raw strings. However, you should still:
- Validate and sanitize inputs.
- Use parameterized queries via Mongoose methods.
Example—unsafe (don’t interpolate strings!):
1CopyEdit// BAD: direct object from user can inject operators
2const filter = req.query.filter;
3Model.find(JSON.parse(filter));
4
1CopyEdit// BAD: direct object from user can inject operators
2const filter = req.query.filter;
3Model.find(JSON.parse(filter));
4
Safe:
1CopyEdit// 1. Validate with a schema (e.g. Zod)
2const validated = FilterSchema.parse(req.query);
3
4// 2. Pass fields explicitly
5Model.find({ name: validated.name, age: validated.age });
6
1CopyEdit// 1. Validate with a schema (e.g. Zod)
2const validated = FilterSchema.parse(req.query);
3
4// 2. Pass fields explicitly
5Model.find({ name: validated.name, age: validated.age });
6
Or use $in, $gt, etc., only with validated data.