Skip to main content

Free 30-min security demo Book Now

Academy NoSQL Injection
Intermediate · 20 min

NoSQL Injection

Discover how MongoDB operator injection bypasses authentication and how typed schemas prevent it.

1 What is NoSQL Injection?

NoSQL databases like MongoDB use query objects instead of SQL strings, but they are still vulnerable to injection when user-supplied data is used directly in query operators.

Vulnerable example (Node.js + MongoDB):

// Attacker sends: { "password": { "$gt": "" } }
const user = await db.collection("users").findOne({
  username: req.body.username,
  password: req.body.password  // injected operator!
});

The $gt operator makes the password condition always true, bypassing authentication. Other operators like $where execute arbitrary JavaScript server-side, enabling data exfiltration.

Tautology attack example:

{ "username": { "$gt": "" }, "password": { "$gt": "" } }

This query returns the first document in the collection, effectively logging in as any user without knowing credentials.

2 Preventing NoSQL Injection

The primary defense is to validate that query parameters are the expected type before using them in queries. Never trust object-shaped input from users.

// Safe — validate types before querying
const { username, password } = req.body;
if (typeof username !== "string" || typeof password !== "string") {
  return res.status(400).json({ error: "Invalid input" });
}
const user = await db.collection("users").findOne({ username, password });

Using Mongoose with strict schemas:

const UserSchema = new mongoose.Schema({
  username: { type: String, required: true },
  password: { type: String, required: true }
});
// Mongoose strict mode (default: true) rejects unknown fields
// Schema typing coerces values to strings, breaking operator injection

Defense checklist:

  • Validate input types (string, not object)
  • Use Mongoose with strict schemas
  • Sanitize operator keys with libraries like mongo-sanitize
  • Disable $where and server-side JS in MongoDB config

Knowledge Check

0/3 correct
Q1

What is the root cause of NoSQL injection in MongoDB?

Q2

Which fix best prevents MongoDB operator injection in a login endpoint?

Q3

How does NoSQL injection differ from SQL injection?

Code Exercise

Fix the MongoDB Login

The login below is vulnerable to NoSQL injection. An attacker can send {"password": {"$gt": ""}} to bypass authentication. Fix it by validating that both username and password are strings.

javascript

Put it into practice

Find NoSQL Injection in your own code

Offensive360 SAST traces the tainted data flow behind this class of bug across 60+ languages and ships a secure fix with every finding. Public open-source projects scan free; teams can see it on their own repository in a 30-minute demo.