Node.js Course
Node.js
/
Intermediate

NoSQL Injection

Definition

Exploiting vulnerabilities in NoSQL databases (like MongoDB) by injecting malicious database query operators through user input.

Explain Like I'm New

People think NoSQL is immune to injection because it doesn't use SQL strings. False! If you pass `req.body` directly into a Mongoose query: `User.find({ email: req.body.email })`, a hacker can send a JSON object instead of a string: `{ "email": { "$gt": "" } }`. This translates to 'Find an email Greater Than nothing', which returns EVERY user in the database.

Real World Example

Bypassing a MongoDB login screen without knowing the password by injecting the `$ne` (Not Equal) operator.

Common Use Cases

  • •Securing MongoDB/Mongoose backends

Interactive Example

// HOW NOSQL INJECTION WORKS

// Expected Input from a normal user:
const normalInput = { username: "Alice", password: "12345" };

// Malicious Input from a hacker (Sending an object instead of a string!)
const hackerInput = { 
  username: "Admin", 
  password: { "$ne": "wrong_password" } // $ne means 'Not Equal'
};

// The Vulnerable Code:
// const user = await User.findOne({
//   username: req.body.username,
//   password: req.body.password 
// });

console.log("If the hacker's input is processed, the query becomes:");
console.log("Find user where username is 'Admin' AND password is NOT EQUAL to 'wrong_password'");
console.log("This evaluates to TRUE, logging the hacker in as the Admin!");

// FIX: npm install express-mongo-sanitize

Interview Questions

basic

  • Can MongoDB be affected by traditional SQL Injection (`' OR '1'='1`)?

intermediate

  • How do you prevent NoSQL Injection in Express?

Flash Cards

Question

Can Mongo be affected by SQL Injection?

Click to reveal answer
Answer

No. MongoDB doesn't understand SQL syntax, so traditional SQL injection attacks fail.

Question

How do you prevent NoSQL injection?

Click to reveal answer
Answer

Data Sanitization. Use middleware like `express-mongo-sanitize`. It intercepts all incoming requests and completely strips out any keys that start with a `$` (the MongoDB operator symbol), neutralizing the attack.