MediumJavaScriptTypeScript

Fix NoSQL Injection

Node.jsSecurityDatabases

The function below builds a MongoDB query filter by embedding user input directly into a $where clause string.

The bug: $where runs its string as raw JavaScript on the database server. An attacker can pass "0'; while(true){}" as the threshold and hang the database with an infinite loop, or pass a boolean-injection payload to bypass the filter entirely and match every document.

This is the real query from OWASP's NodeGoat (a deliberately-vulnerable Node.js app used for security training):

return {
  $where: `this.userId == ${parsedUserId} && this.stocks > '${threshold}'`
};

Your task: fix solve(userId, threshold) so it returns a filter object built from standard MongoDB query operators instead of an interpolated $where string:

// Expected return shape
{ userId: userId, stocks: { $gt: threshold } }

Sample tests

Test #1Normal numeric threshold
Input: [1,100]
Output: {"stocks":{"$gt":100},"userId":1}
Test #2Zero threshold
Input: [42,0]
Output: {"stocks":{"$gt":0},"userId":42}
Test #3Infinite-loop payload stays inert as a plain value
Input: [1,"0'; while(true){}"]
Output: {"stocks":{"$gt":"0'; while(true){}"},"userId":1}