GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Express

NoSQL injection in the Express/Mongoose stack is a silent killer. It exploits the way MongoDB drivers handle objects in query filters. If your middleware doesn't strictly validate types, an attacker can swap a string for an operator object like {'$gt': ''}, bypassing authentication or dumping the entire collection. If you're passing raw req.body into your find() calls, your database is essentially public.

The Vulnerable Pattern

app.post('/api/login', async (req, res) => {
  // VULNERABLE: If req.body.password is { "$ne": null }, the check passes for any user.
  const user = await User.findOne({
    username: req.body.username,
    password: req.body.password
  });

if (user) { res.status(200).json({ success: true }); } else { res.status(401).json({ error: ‘Invalid credentials’ }); } });

The Secure Implementation

The exploit works because Express's body-parser parses JSON objects recursively. An attacker sends 'Content-Type: application/json' with a body of {'username': 'admin', 'password': {'$ne': ''}}. Without sanitization, Mongoose executes a query looking for a user where the password is 'not equal to empty string'—which is always true. To fix this, use 'mongo-sanitize' to recursively strip any object keys beginning with '$', and explicitly cast inputs to Strings to ensure that even if an object bypasses the filter, it is treated as a literal value rather than a query operator.

const sanitize = require('mongo-sanitize');

app.post(‘/api/login’, async (req, res) => { // SECURE: 1. Sanitize to strip any keys starting with ’$’ const cleanUsername = sanitize(req.body.username); const cleanPassword = sanitize(req.body.password);

// SECURE: 2. Force type casting to String to prevent operator injection const user = await User.findOne({ username: String(cleanUsername), password: String(cleanPassword) });

if (user) { res.status(200).json({ success: true }); } else { res.status(401).json({ error: ‘Invalid credentials’ }); } });

System Alert • ID: 5924
Target: Express API
Potential Vulnerability

Your Express API might be exposed to NoSQL Injection

74% of Express apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.