NoSQL injection: how a JSON value becomes a query operator, and how to stop it
NoSQL injection is input changing the question your application asks a document database: as an object where your code expected text, which is operator injection, or as code the database runs on the server.
This guide explains it in plain English, then gives you a lab to run on your own machine with Node.js alone: one small API in a flawed version and three fixed ones, the filter each one sent to the database layer, and regression tests that fail until the fix is in.
In this guide
NoSQL injection lab: one value sent as an object, three fixes and their tests
An illustration, not a client system: an invented bike repair workshop with three customers and four repairs, held in an in-memory stand-in for a document database. Four files run with Node.js alone. lab.mjs sends ordinary and object-valued requests to a sign-in route, a tracking lookup and a filtered search, in a flawed version and in versions fixed by schema validation, an operator allow-list and casting, and prints the filter each version passed to the data layer and the response. regression.test.mjs fails on the flawed version and passes on each fixed one.
How to use itHide the instructions
Zod, Mongoose and MongoDB equivalents follow. Run it on your own machine, for learning and for testing code you own.
nosql-injection.txt
ILLUSTRATION ONLY. The bike repair workshop, its three customers, their passwords and their four repairs are invented. collection.mjs stands in for a document database: it holds the records in memory, understands plain equality and five comparison operators, and records every filter it receives. It proves what your own code passes to the database layer. What a real database does with an operator is set out in that database's own documentation, cited on the page. Use this lab for learning and for testing code you own. Sending operator input to a system you do not own, without the owner's written authority, is not something this lab is for.
Needs: Node.js 20.0.0 or later. The Node.js documentation marks node:test stable from 20.0.0, and fetch() is no longer behind the --experimental-fetch flag from 18.0.0 and no longer experimental from 21.0.0. The lab imports only node:http, node:test and node:assert/strict, calls the global fetch(), and installs no packages.
Written and run on: Node.js 26.0.0. Every output below comes from that run. Test timings will differ on your machine.
Setup: make an empty folder, save the four files below into it with the names shown, and open a terminal in that folder.
================================================================
FILE 1 OF 4: collection.mjs
================================================================
// collection.mjs: a stand-in for a document database, held in memory.
// Illustration only: an invented bike repair workshop with invented records.
// It understands plain equality and five comparison operators, which is
// enough to show what a filter object asks for. A real database supports
// many more operators, so this proves what your code sends, not what a
// particular database does with it.
export function createWorkshopData(onQuery) {
const users = createCollection('users', [
{ username: 'ava', password: 'lab-only-ava-pw' },
{ username: 'ben', password: 'lab-only-ben-pw' },
{ username: 'chloe', password: 'lab-only-chloe-pw' },
], onQuery)
// A tracking code covers every bike dropped off together, so Ava's two
// bikes share one code.
const repairs = createCollection('repairs', [
{ jobNumber: 4471, trackingCode: 'TRK-7KQ2', customer: 'ava', status: 'ready', daysIn: 2 },
{ jobNumber: 4472, trackingCode: 'TRK-7KQ2', customer: 'ava', status: 'in-progress', daysIn: 2 },
{ jobNumber: 4473, trackingCode: 'TRK-W9DL', customer: 'ben', status: 'waiting-parts', daysIn: 6 },
{ jobNumber: 4474, trackingCode: 'TRK-C5HV', customer: 'chloe', status: 'ready', daysIn: 1 },
], onQuery)
return { users: users, repairs: repairs }
}
function createCollection(name, documents, onQuery) {
return {
find(filter) {
onQuery(name, filter)
const matches = documents.filter((document) => matchesFilter(document, filter))
return matches.map((document) => Object.assign({}, document))
},
findOne(filter) {
const matches = this.find(filter)
return matches.length > 0 ? matches.at(0) : null
},
}
}
export function matchesFilter(document, filter) {
for (const field of Object.keys(filter)) {
if (!matchesCondition(document[field], filter[field])) return false
}
return true
}
// A condition is either a plain value to compare, or an object whose keys
// are all operators, such as { "$ne": "" }.
function matchesCondition(value, condition) {
if (!isOperatorObject(condition)) return valuesEqual(value, condition)
for (const operator of Object.keys(condition)) {
if (!applyOperator(value, operator, condition[operator])) return false
}
return true
}
function isOperatorObject(condition) {
if (condition === null || typeof condition !== 'object' || Array.isArray(condition)) return false
const keys = Object.keys(condition)
return keys.length > 0 && keys.every((key) => key.startsWith('$'))
}
function applyOperator(value, operator, operand) {
if (operator === '$eq') return valuesEqual(value, operand)
// Not equal also matches records that lack the field.
if (operator === '$ne') return !valuesEqual(value, operand)
if (operator === '$in') return Array.isArray(operand) && operand.some((item) => valuesEqual(value, item))
if (operator === '$gte') return typeof value === typeof operand && value >= operand
if (operator === '$lte') return typeof value === typeof operand && value <= operand
throw new Error('This lab does not support the operator ' + operator)
}
// Objects compare field by field in order.
function valuesEqual(left, right) {
return JSON.stringify(left) === JSON.stringify(right)
}
================================================================
FILE 2 OF 4: handlers.mjs
================================================================
// handlers.mjs: one workshop API in four versions. Each handler takes the
// parsed JSON body and the data, and returns a status, a response body and,
// sometimes, a note for the server log.
// Passwords are stored as plain text only to keep the lab short. A real
// sign-in stores a slow hash and checks it in code.
// The repairs search treats every request as coming from this customer.
export const SIGNED_IN_CUSTOMER = 'ava'
function signInResult(user) {
if (!user) return { status: 401, body: { error: 'Sign-in failed' } }
return { status: 200, body: { signedInAs: user.username } }
}
function repairsResult(repairs) {
const list = repairs.map((repair) => ({ jobNumber: repair.jobNumber, customer: repair.customer, status: repair.status }))
return { status: 200, body: { repairs: list } }
}
function badRequest(message, note) {
return { status: 400, body: { error: message }, note: note }
}
function isPlainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value)
}
// ---------------------------------------------------------------------------
// VERSION 1, FLAWED: request values go straight into the filter.
// ---------------------------------------------------------------------------
const flawed = {
signIn(body, data) {
return signInResult(data.users.findOne({ username: body.username, password: body.password }))
},
trackRepair(body, data) {
return repairsResult(data.repairs.find({ trackingCode: body.trackingCode }))
},
searchMyRepairs(body, data) {
// The customer is set first, so a customer key in the request replaces it.
const filter = Object.assign({ customer: SIGNED_IN_CUSTOMER }, body.filter)
return repairsResult(data.repairs.find(filter))
},
}
// ---------------------------------------------------------------------------
// VERSION 2, VALIDATED: each route checks the shape of the body before any
// query runs. Every listed field must be a string of a sensible length, and
// any field the route does not expect is refused.
// ---------------------------------------------------------------------------
const SIGN_IN_SHAPE = { username: { maxLength: 64 }, password: { maxLength: 256 } }
const TRACK_SHAPE = { trackingCode: { maxLength: 16 } }
function checkShape(body, shape) {
if (!isPlainObject(body)) return { error: 'Body must be a JSON object' }
for (const field of Object.keys(body)) {
if (!Object.hasOwn(shape, field)) return { error: field + ' is not expected' }
}
const values = {}
for (const field of Object.keys(shape)) {
const value = body[field]
const maxLength = shape[field].maxLength
if (typeof value !== 'string') return { error: field + ' must be a string' }
if (value.length === 0 || value.length > maxLength) return { error: field + ' must be 1 to ' + maxLength + ' characters' }
values[field] = value
}
return { values: values }
}
const validated = {
signIn(body, data) {
const checked = checkShape(body, SIGN_IN_SHAPE)
if (checked.error) return badRequest(checked.error)
return signInResult(data.users.findOne({ username: checked.values.username, password: checked.values.password }))
},
trackRepair(body, data) {
const checked = checkShape(body, TRACK_SHAPE)
if (checked.error) return badRequest(checked.error)
return repairsResult(data.repairs.find({ trackingCode: checked.values.trackingCode }))
},
}
// ---------------------------------------------------------------------------
// VERSION 3, ALLOW-LISTED: each route lists the fields it filters on, the
// operators allowed on each, and the type each value must have. Sign-in and
// tracking allow plain equality only. The repairs search takes a filter on
// purpose, so it also allows $in on status and a range on daysIn.
// ---------------------------------------------------------------------------
const SIGN_IN_RULES = {
username: { type: 'string', operators: ['$eq'], required: true },
password: { type: 'string', operators: ['$eq'], required: true },
}
const TRACK_RULES = { trackingCode: { type: 'string', operators: ['$eq'], required: true } }
const SEARCH_RULES = {
status: { type: 'string', operators: ['$eq', '$in'], required: false },
daysIn: { type: 'number', operators: ['$gte', '$lte'], required: false },
}
function buildAllowedFilter(input, rules) {
if (!isPlainObject(input)) return { error: 'Filter must be a JSON object' }
for (const field of Object.keys(rules)) {
if (rules[field].required && !Object.hasOwn(input, field)) return { error: field + ' is required' }
}
const filter = {}
for (const field of Object.keys(input)) {
if (!Object.hasOwn(rules, field)) return { error: field + ' is not a field this route filters on' }
const problem = checkCondition(field, input[field], rules[field])
if (problem) return { error: problem }
filter[field] = input[field]
}
return { filter: filter }
}
// A condition is a plain value of the field's type, or an object made only
// of operators from the field's list, each with a value of the right type.
function checkCondition(field, condition, rule) {
if (typeof condition === rule.type) return null
if (!isPlainObject(condition) || Object.keys(condition).length === 0) {
return field + ' must be a ' + rule.type + ' or use an allowed operator'
}
for (const operator of Object.keys(condition)) {
if (!rule.operators.includes(operator)) return operator + ' is not allowed on ' + field
if (!hasAllowedOperand(operator, condition[operator], rule.type)) return 'Wrong value type for ' + operator + ' on ' + field
}
return null
}
function hasAllowedOperand(operator, operand, type) {
if (operator === '$in') return Array.isArray(operand) && operand.every((item) => typeof item === type)
return typeof operand === type
}
const allowlisted = {
signIn(body, data) {
const built = buildAllowedFilter(body, SIGN_IN_RULES)
if (built.error) return badRequest(built.error)
return signInResult(data.users.findOne(built.filter))
},
trackRepair(body, data) {
const built = buildAllowedFilter(body, TRACK_RULES)
if (built.error) return badRequest(built.error)
return repairsResult(data.repairs.find(built.filter))
},
searchMyRepairs(body, data) {
if (!isPlainObject(body)) return badRequest('Body must be a JSON object')
const built = buildAllowedFilter(body.filter, SEARCH_RULES)
if (built.error) return badRequest(built.error)
// The signed-in customer goes in last, so nothing in the request replaces it.
built.filter.customer = SIGNED_IN_CUSTOMER
return repairsResult(data.repairs.find(built.filter))
},
}
// ---------------------------------------------------------------------------
// VERSION 4, CAST: the handlers pass values on as the flawed version does,
// and the data layer casts each value to the type its field holds before it
// builds the filter. A value that cannot become that type is refused.
// ---------------------------------------------------------------------------
function castToText(value, field) {
if (typeof value === 'string') return value
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
const error = new Error('cannot cast ' + describeType(value) + ' to text for ' + field)
error.name = 'CastError'
throw error
}
function describeType(value) {
if (value === undefined) return 'a missing value'
if (value === null) return 'null'
if (Array.isArray(value)) return 'an array'
return 'an ' + typeof value
}
// The data layer: in this version, the only functions that build filters.
function findUserByCredentials(data, username, password) {
const filter = { username: castToText(username, 'username'), password: castToText(password, 'password') }
return data.users.findOne(filter)
}
function findRepairsByTrackingCode(data, trackingCode) {
return data.repairs.find({ trackingCode: castToText(trackingCode, 'trackingCode') })
}
function refuseCast(error) {
if (error.name !== 'CastError') throw error
return badRequest('Invalid request', 'CastError: ' + error.message)
}
const cast = {
signIn(body, data) {
try {
return signInResult(findUserByCredentials(data, body.username, body.password))
} catch (error) {
return refuseCast(error)
}
},
trackRepair(body, data) {
try {
return repairsResult(findRepairsByTrackingCode(data, body.trackingCode))
} catch (error) {
return refuseCast(error)
}
},
}
export const versions = { flawed: flawed, validated: validated, allowlisted: allowlisted, cast: cast }
================================================================
FILE 3 OF 4: lab.mjs
================================================================
// lab.mjs: a local web server running all four versions, and the requests
// that show the difference. It listens on 127.0.0.1, on a port the system
// picks, and stops when the requests are done.
import { createServer } from 'node:http'
import { createWorkshopData } from './collection.mjs'
import { versions } from './handlers.mjs'
const ROUTES = { '/signin': 'signIn', '/repairs/track': 'trackRepair', '/repairs/search': 'searchMyRepairs' }
// Each filter the data layer receives is written down here, then printed.
let filtersThisRequest = []
const data = createWorkshopData(function recordFilter(collectionName, filter) {
filtersThisRequest.push(' Filter sent to ' + collectionName + ': ' + JSON.stringify(filter))
})
function sendJson(response, status, body) {
response.writeHead(status, { 'content-type': 'application/json' })
response.end(JSON.stringify(body))
}
function readBody(request) {
return new Promise((resolve) => {
let text = ''
request.on('data', (chunk) => {
text += chunk
})
request.on('end', () => resolve(text))
})
}
// Like a JSON body parser: the text becomes whatever value it describes.
// Only objects and arrays are accepted as a body.
function parseJsonBody(text) {
try {
const value = JSON.parse(text)
return typeof value === 'object' && value !== null ? value : undefined
} catch {
return undefined
}
}
function findHandler(path) {
const parts = path.split('/')
const versionName = parts.at(1)
const routeName = ROUTES['/' + parts.slice(2).join('/')]
if (!Object.hasOwn(versions, versionName) || !routeName) return undefined
return versions[versionName][routeName]
}
async function handleRequest(request, response) {
const handler = findHandler(request.url)
if (!handler) return sendJson(response, 404, { error: 'Not in this version' })
const body = parseJsonBody(await readBody(request))
if (body === undefined) return sendJson(response, 400, { error: 'Body must be a JSON object' })
filtersThisRequest = []
const result = handler(body, data)
for (const line of filtersThisRequest) console.log(line)
if (filtersThisRequest.length === 0) console.log(' No query sent.')
if (result.note) console.log(' Server log: ' + result.note)
sendJson(response, result.status, result.body)
}
const ALL_VERSIONS = ['flawed', 'validated', 'allowlisted', 'cast']
const FILTER_ROUTE_VERSIONS = ['flawed', 'allowlisted']
const requests = [
{
label: 'A1 Sign-in with the right password',
route: '/signin',
versionNames: ALL_VERSIONS,
body: { username: 'ava', password: 'lab-only-ava-pw' },
},
{
label: 'A2 Sign-in with the password sent as an object',
route: '/signin',
versionNames: ALL_VERSIONS,
body: { username: 'ava', password: { $ne: '' } },
},
{
label: 'B1 Track a repair with a real tracking code',
route: '/repairs/track',
versionNames: ALL_VERSIONS,
body: { trackingCode: 'TRK-7KQ2' },
},
{
label: 'B2 Track a repair with the code sent as an object',
route: '/repairs/track',
versionNames: ALL_VERSIONS,
body: { trackingCode: { $ne: '' } },
},
{
label: 'C1 Search my repairs with an operator the route allows',
route: '/repairs/search',
versionNames: FILTER_ROUTE_VERSIONS,
body: { filter: { status: { $in: ['ready', 'waiting-parts'] } } },
},
{
label: 'C2 Search my repairs with the customer field sent as an object',
route: '/repairs/search',
versionNames: FILTER_ROUTE_VERSIONS,
body: { filter: { customer: { $ne: '' } } },
},
]
async function sendRequest(port, versionName, route, body) {
const path = '/' + versionName + route
console.log(' ' + versionName.padEnd(12) + 'POST ' + path)
const response = await fetch('http://127.0.0.1:' + port + path, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
})
console.log(' Response: ' + response.status + ' ' + (await response.text()))
}
const server = createServer(handleRequest)
server.listen(0, '127.0.0.1', async () => {
const port = server.address().port
for (const request of requests) {
console.log(request.label)
console.log(' Body sent: ' + JSON.stringify(request.body))
for (const versionName of request.versionNames) {
await sendRequest(port, versionName, request.route, request.body)
}
}
server.close()
})
================================================================
FILE 4 OF 4: regression.test.mjs
================================================================
// regression.test.mjs: fails while a value sent as an object can change
// what a lookup matches.
// Run: node regression.test.mjs flawed (expect failures)
// node regression.test.mjs validated (expect every test to pass)
// node regression.test.mjs allowlisted (expect every test to pass)
// node regression.test.mjs cast (expect every test to pass)
// With no argument it tests the validated version, which is what
// node --test runs in a pipeline.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { createWorkshopData } from './collection.mjs'
import { versions } from './handlers.mjs'
const versionName = process.argv.at(2) || 'validated'
if (!Object.hasOwn(versions, versionName)) throw new Error('Unknown version: ' + versionName)
const version = versions[versionName]
const data = createWorkshopData(function ignoreFilter() {})
function signedInAs(body) {
return version.signIn(body, data).body.signedInAs || null
}
function listJobNumbers(result) {
const repairs = result.body.repairs || []
return repairs.map((repair) => repair.jobNumber)
}
test(versionName + ': the right password signs in', () => {
assert.equal(signedInAs({ username: 'ava', password: 'lab-only-ava-pw' }), 'ava')
})
test(versionName + ': a wrong password does not sign in', () => {
assert.equal(signedInAs({ username: 'ava', password: 'not-the-password' }), null)
})
test(versionName + ': a password sent as an object does not sign in', () => {
assert.equal(signedInAs({ username: 'ava', password: { $ne: '' } }), null)
})
test(versionName + ': a username sent as an object does not sign in', () => {
assert.equal(signedInAs({ username: { $ne: '' }, password: 'lab-only-ava-pw' }), null)
})
test(versionName + ': a real tracking code returns only its own repairs', () => {
assert.deepEqual(listJobNumbers(version.trackRepair({ trackingCode: 'TRK-7KQ2' }, data)), [4471, 4472])
})
test(versionName + ': a tracking code sent as an object returns no repairs', () => {
assert.deepEqual(listJobNumbers(version.trackRepair({ trackingCode: { $ne: '' } }, data)), [])
})
// Only the versions that offer the repairs search, which takes a filter on purpose.
if (version.searchMyRepairs) {
test(versionName + ': an allowed operator searches only the signed-in customer', () => {
const body = { filter: { status: { $in: ['ready', 'waiting-parts'] } } }
assert.deepEqual(listJobNumbers(version.searchMyRepairs(body, data)), [4471])
})
test(versionName + ': a customer field sent as an object cannot widen the search', () => {
const body = { filter: { customer: { $ne: '' } } }
assert.deepEqual(listJobNumbers(version.searchMyRepairs(body, data)), [])
})
}
================================================================
STEP 1: send the requests
================================================================
Command: node lab.mjs
A1 Sign-in with the right password
Body sent: {"username":"ava","password":"lab-only-ava-pw"}
flawed POST /flawed/signin
Filter sent to users: {"username":"ava","password":"lab-only-ava-pw"}
Response: 200 {"signedInAs":"ava"}
validated POST /validated/signin
Filter sent to users: {"username":"ava","password":"lab-only-ava-pw"}
Response: 200 {"signedInAs":"ava"}
allowlisted POST /allowlisted/signin
Filter sent to users: {"username":"ava","password":"lab-only-ava-pw"}
Response: 200 {"signedInAs":"ava"}
cast POST /cast/signin
Filter sent to users: {"username":"ava","password":"lab-only-ava-pw"}
Response: 200 {"signedInAs":"ava"}
A2 Sign-in with the password sent as an object
Body sent: {"username":"ava","password":{"$ne":""}}
flawed POST /flawed/signin
Filter sent to users: {"username":"ava","password":{"$ne":""}}
Response: 200 {"signedInAs":"ava"}
validated POST /validated/signin
No query sent.
Response: 400 {"error":"password must be a string"}
allowlisted POST /allowlisted/signin
No query sent.
Response: 400 {"error":"$ne is not allowed on password"}
cast POST /cast/signin
No query sent.
Server log: CastError: cannot cast an object to text for password
Response: 400 {"error":"Invalid request"}
B1 Track a repair with a real tracking code
Body sent: {"trackingCode":"TRK-7KQ2"}
flawed POST /flawed/repairs/track
Filter sent to repairs: {"trackingCode":"TRK-7KQ2"}
Response: 200 {"repairs":[{"jobNumber":4471,"customer":"ava","status":"ready"},{"jobNumber":4472,"customer":"ava","status":"in-progress"}]}
validated POST /validated/repairs/track
Filter sent to repairs: {"trackingCode":"TRK-7KQ2"}
Response: 200 {"repairs":[{"jobNumber":4471,"customer":"ava","status":"ready"},{"jobNumber":4472,"customer":"ava","status":"in-progress"}]}
allowlisted POST /allowlisted/repairs/track
Filter sent to repairs: {"trackingCode":"TRK-7KQ2"}
Response: 200 {"repairs":[{"jobNumber":4471,"customer":"ava","status":"ready"},{"jobNumber":4472,"customer":"ava","status":"in-progress"}]}
cast POST /cast/repairs/track
Filter sent to repairs: {"trackingCode":"TRK-7KQ2"}
Response: 200 {"repairs":[{"jobNumber":4471,"customer":"ava","status":"ready"},{"jobNumber":4472,"customer":"ava","status":"in-progress"}]}
B2 Track a repair with the code sent as an object
Body sent: {"trackingCode":{"$ne":""}}
flawed POST /flawed/repairs/track
Filter sent to repairs: {"trackingCode":{"$ne":""}}
Response: 200 {"repairs":[{"jobNumber":4471,"customer":"ava","status":"ready"},{"jobNumber":4472,"customer":"ava","status":"in-progress"},{"jobNumber":4473,"customer":"ben","status":"waiting-parts"},{"jobNumber":4474,"customer":"chloe","status":"ready"}]}
validated POST /validated/repairs/track
No query sent.
Response: 400 {"error":"trackingCode must be a string"}
allowlisted POST /allowlisted/repairs/track
No query sent.
Response: 400 {"error":"$ne is not allowed on trackingCode"}
cast POST /cast/repairs/track
No query sent.
Server log: CastError: cannot cast an object to text for trackingCode
Response: 400 {"error":"Invalid request"}
C1 Search my repairs with an operator the route allows
Body sent: {"filter":{"status":{"$in":["ready","waiting-parts"]}}}
flawed POST /flawed/repairs/search
Filter sent to repairs: {"customer":"ava","status":{"$in":["ready","waiting-parts"]}}
Response: 200 {"repairs":[{"jobNumber":4471,"customer":"ava","status":"ready"}]}
allowlisted POST /allowlisted/repairs/search
Filter sent to repairs: {"status":{"$in":["ready","waiting-parts"]},"customer":"ava"}
Response: 200 {"repairs":[{"jobNumber":4471,"customer":"ava","status":"ready"}]}
C2 Search my repairs with the customer field sent as an object
Body sent: {"filter":{"customer":{"$ne":""}}}
flawed POST /flawed/repairs/search
Filter sent to repairs: {"customer":{"$ne":""}}
Response: 200 {"repairs":[{"jobNumber":4471,"customer":"ava","status":"ready"},{"jobNumber":4472,"customer":"ava","status":"in-progress"},{"jobNumber":4473,"customer":"ben","status":"waiting-parts"},{"jobNumber":4474,"customer":"chloe","status":"ready"}]}
allowlisted POST /allowlisted/repairs/search
No query sent.
Response: 400 {"error":"customer is not a field this route filters on"}
Reading the evidence:
A1 The right password. Every version sends the same filter and signs Ava in.
A2 The password arrives as an object holding the operator $ne and an empty string. The flawed version puts it in the filter unchanged, so the filter asks for Ava with any password that is not empty, and she is signed in without one. The validated version rejects the body because password is not a string, the allow-listed version rejects the operator, and the cast version's data layer refuses to turn an object into text. None of the three sends a query.
B1 A real tracking code. Every version returns Ava's two repairs, which were dropped off together.
B2 The code arrives as the same object. The flawed filter asks for every repair whose code is not empty, and the response lists all four, including Ben's and Chloe's. The three fixed versions refuse it before any query, as in A2.
C1 The repairs search takes a filter on purpose. $in on status is on the route's allow-list, so both versions run it and return Ava's one ready repair. Ben's repair, which is waiting for parts, stays out because the signed-in customer is part of the filter.
C2 The flawed version sets the signed-in customer first and copies the request's filter over it, so a customer field holding the same object replaces Ava's ID and the response lists all four repairs. The allow-listed version refuses a field that is not on its list, and adds the signed-in customer after the request's filter in any case.
================================================================
STEP 2: run the regression tests against the flawed version
================================================================
Command: node regression.test.mjs flawed
✔ flawed: the right password signs in (0.848917ms)
✔ flawed: a wrong password does not sign in (0.058459ms)
✖ flawed: a password sent as an object does not sign in (0.79625ms)
✖ flawed: a username sent as an object does not sign in (0.127916ms)
✔ flawed: a real tracking code returns only its own repairs (0.747708ms)
✖ flawed: a tracking code sent as an object returns no repairs (0.664959ms)
✔ flawed: an allowed operator searches only the signed-in customer (0.079875ms)
✖ flawed: a customer field sent as an object cannot widen the search (0.10125ms)
ℹ tests 8
ℹ suites 0
ℹ pass 4
ℹ fail 4
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.358042
✖ failing tests:
test at regression.test.mjs:37:1
✖ flawed: a password sent as an object does not sign in (0.79625ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
'ava' !== null
(stack trace and error properties removed here)
(the failure block for the username case is cut here; it fails the same way as the password case)
test at regression.test.mjs:49:1
✖ flawed: a tracking code sent as an object returns no repairs (0.664959ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 4471,
+ 4472,
+ 4473,
+ 4474
+ ]
- []
(stack trace and error properties removed here)
(the failure block for the customer field case is cut here; it fails the same way as the tracking code case)
The process exits with code 1, so a pipeline step that runs these tests fails.
================================================================
STEP 3: run them against each fixed version
================================================================
Command: node regression.test.mjs validated
✔ validated: the right password signs in (0.782791ms)
✔ validated: a wrong password does not sign in (0.07325ms)
✔ validated: a password sent as an object does not sign in (0.056541ms)
✔ validated: a username sent as an object does not sign in (0.048959ms)
✔ validated: a real tracking code returns only its own repairs (0.682875ms)
✔ validated: a tracking code sent as an object returns no repairs (0.050667ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5.685667
Command: node regression.test.mjs allowlisted
✔ allowlisted: the right password signs in (0.837875ms)
✔ allowlisted: a wrong password does not sign in (0.060833ms)
✔ allowlisted: a password sent as an object does not sign in (0.070208ms)
✔ allowlisted: a username sent as an object does not sign in (0.057291ms)
✔ allowlisted: a real tracking code returns only its own repairs (0.726ms)
✔ allowlisted: a tracking code sent as an object returns no repairs (0.049584ms)
✔ allowlisted: an allowed operator searches only the signed-in customer (0.129833ms)
✔ allowlisted: a customer field sent as an object cannot widen the search (0.053208ms)
ℹ tests 8
ℹ suites 0
ℹ pass 8
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6.629334
Command: node regression.test.mjs cast
✔ cast: the right password signs in (0.710208ms)
✔ cast: a wrong password does not sign in (0.067708ms)
✔ cast: a password sent as an object does not sign in (0.072542ms)
✔ cast: a username sent as an object does not sign in (0.0465ms)
✔ cast: a real tracking code returns only its own repairs (0.652875ms)
✔ cast: a tracking code sent as an object returns no repairs (0.050959ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5.473041
Each run exits with code 0. The validated and cast versions have six tests because they do not offer the repairs search, which takes a filter on purpose and is the allow-list's job. With no argument the file tests the validated version, so node --test finds it in a pipeline by its .test.mjs name.
================================================================
STEP 4: the same defences with Zod, Mongoose and the explicit $eq form
================================================================
Not run in this lab. Each snippet follows its project's documentation, cited on the page.
Zod (z.strictObject(), z.string() with .min() and .max(), and .safeParse(), as on Zod's API and basic usage pages):
import * as z from 'zod'
const SignInBody = z.strictObject({
username: z.string().min(1).max(64),
password: z.string().min(1).max(256),
})
const result = SignInBody.safeParse(body)
if (!result.success) {
// Answer 400 here. Below this point, result.data.username and
// result.data.password are strings.
}
Avoid z.coerce.string() for these fields. Zod documents it as String(input), which converts a value instead of rejecting it.
Mongoose (from its schemas guide and API reference; sanitizeFilter is false by default):
// Not this: the request's query object becomes the filter.
const docs = await MyModel.find(req.query)
// This: name each field, and turn on sanitizeFilter for the query.
const docs = await MyModel.find({ name: req.query.name, age: req.query.age }).setOptions({ sanitizeFilter: true })
// Or turn it on for every query:
mongoose.set('sanitizeFilter', true)
MongoDB's explicit $eq form (its $eq page asks for this form with user-supplied input):
const filter = { trackingCode: { $eq: trackingCode } }
Keep the string check in front of it. The route should still refuse a value of the wrong type.
Patterns to search your own code for:
find(req.body), find(req.query), findOne(req.body), or a filter built by copying or spreading request data
Object.assign or a spread that puts request data over a value your code set, such as the signed-in customer
$where, $function, $accumulator and mapReduce anywhere a request value can reach
trusted( in Mongoose code, which tells sanitizeFilter to skip that object
strictQuery: true, which removes filter paths that are not in the schema, so a query can match more documents
express.urlencoded({ extended: true }) and app.set('query parser', 'extended'), which build nested objects from square brackets in names
================================================================
STEP 5: point the tests at your own code
================================================================
1. Copy regression.test.mjs into your project's tests.
2. Change signedInAs to call your real sign-in handler or data access function with a test account, and the tracking and search calls to your real lookups, against a test database that holds records for at least two customers.
3. Keep the ordinary cases and the object cases. Add an object case for every field that reaches a filter: password reset and invitation codes, record IDs, and the fields of any search or list filter.
4. If a route reads a query string or a form under a parser that builds objects from square brackets, add a case that sends the marker that way, for example ?trackingCode[$ne]=x on a GET route.
5. Run the tests in the pipeline that deploys your app. A failure on an object case means a value of the wrong type reached a filter. A failure on an ordinary case means the fix, or the validation, is turning away real input.What NoSQL injection is
Document databases such as MongoDB store records as documents that look like JSON, and an application asks for them with a filter: an object that says which fields must hold which values.
A sign-in asks for the user whose username is the one typed in and whose password matches. NoSQL injection happens when input from the request changes that question. In operator injection, the form the lab on this page shows, a value in the filter comes from the request and the request sends an object instead of the plain value the code expected, so the filter asks a different question.
Input that reaches JavaScript the database runs on the server is a second form, covered in the next section.
MITRE catalogues the weakness as CWE-943, Improper Neutralization of Special Elements in Data Query Logic, and lists NoSQL Injection and NoSQLi as alternate terms, for injection of data query language into NoSQL databases such as Cassandra, ElasticSearch, MongoDB and Redis. Its description says the product generates a query to access or manipulate data in a data store but does not neutralise, or incorrectly neutralises, special elements that can modify the intended logic of the query.
OWASP's Injection Prevention Cheat Sheet, which says injection flaws occur when an application sends untrusted data to an interpreter, lists NoSQL injection among its forms of injection, for code that builds queries for a NoSQL database.
The OWASP Top 10:2025 names NoSQL among some of the more common injections in its A05 Injection category.
CWE-943 sets out what changed query logic can do, depending on the capabilities of the query language: change the selection criteria, append commands, return more or fewer records than intended, or sort them in an unexpected way. It adds that logic depending on the number or order of records is at risk too: if a query is expected to return only an administrative user and an attacker can change which record comes back, the logic could return a regular user and wrongly assume that user has administrative privileges.
In the lab on this page the same kind of change turns a sign-in into a sign-in without the password, and a lookup by tracking code into a list of every customer's repairs.
In business terms: your code asks the database a question with a blank for the visitor to fill in. If the visitor can fill the blank with another question instead of an answer, the database answers that question. The fix is to make sure each blank holds an answer of the expected type before the question is asked.
This page is about document databases and the request bodies, forms and query strings that feed them. SQL databases have their own guide in this library, with a lab of their own.
Why NoSQL does not mean no injection
The name invites a wrong conclusion: no SQL, so no SQL injection, so nothing to inject.
MongoDB's FAQ, in its version 9.0 manual, explains the part that is true. A client program builds a MongoDB query as a BSON object, not a string, so traditional SQL injection attacks are not a problem, and client libraries typically provide a convenient, injection free process to build those objects.
In its example, special characters inside a value, such as a comma, a colon or an opening brace, simply mean the query matches no documents, and a user cannot turn the query into a delete.
That holds while the value is a string. OWASP's NoSQL Security Cheat Sheet names the gap: building a query object does not prevent operator injection when an untrusted value is itself an object. Its example is { name: { $ne: "" } }, which MongoDB interprets as a not-equal query, and its advice is to validate the expected scalar type before constructing the filter and not to pass client-supplied objects through as field values.
MongoDB's documentation says what that operator asks for. $ne selects documents where the value of the field is not equal to the specified value, and that includes documents that do not contain the field at all. So a password of { $ne: "" } asks for any password that is not an empty string, and a tracking code of { $ne: "" } asks for every record whose code is not empty, or that has no code.
OWASP's Web Security Testing Guide v4.2 adds two warnings. Filtering out HTML special characters such as < > & and ; will not prevent attacks against a JSON API, where the special characters include / { } and :. And because NoSQL injection attacks may execute within a procedural language rather than in the declarative SQL language, the guide says the potential impacts are greater than traditional SQL injection.
In MongoDB that procedural language is server-side JavaScript. The FAQ lists four operations that let arbitrary JavaScript expressions run directly on the server, $where, mapReduce, $accumulator and $function, says you must exercise care in these cases to prevent users from submitting malicious JavaScript, and notes that most operations can be expressed without it.
It also gives the switch: the --noscripting option, or security.javascriptEnabled set to false in the configuration file, disables all server-side execution of JavaScript for mongod or mongos. The lab on this page uses none of these operations, and none of them should be reachable from a request.
NoSQL operator injection, step by step
The lab on this page uses one invented business so every step can be shown with real output: a bike repair workshop whose customers sign in with a username and password, and can check on a repair with the tracking code printed on their ticket.
One code covers every bike dropped off together, so a tracking lookup returns a list. The flawed version copies values from the JSON body straight into the filter. Here is what the database layer received, request by request, and what came back.
- Sign-in, ordinary. The body {"username":"ava","password":"lab-only-ava-pw"} becomes the filter {"username":"ava","password":"lab-only-ava-pw"}, and the response is 200 with signedInAs set to ava. Every version agrees.
- Sign-in, with the password sent as an object. The body {"username":"ava","password":{"$ne":""}} reaches the database layer unchanged, as the filter {"username":"ava","password":{"$ne":""}}: find Ava, with any password that is not empty. The flawed version answers 200 and signs Ava in without her password.
- Tracking, ordinary. The body {"trackingCode":"TRK-7KQ2"} becomes the filter {"trackingCode":"TRK-7KQ2"}, and the response lists Ava's two repairs, jobs 4471 and 4472.
- Tracking, with the code sent as an object. The body {"trackingCode":{"$ne":""}} becomes the filter {"trackingCode":{"$ne":""}}, and the response lists all four repairs in the collection, including Ben's and Chloe's.
Why the object gets through
Nothing in the flawed code looks unusual. It reads body.password and puts it in the filter, the way it would read a form field. By then the JSON parser has already turned the text {"$ne":""} into a JavaScript object, so the code is holding an object where it expected text, and the filter it builds has an operator where it expected a value.
No quote mark was broken and nothing was joined into a string, so defences written for SQL, such as escaping quotes, have nothing to act on.
The marker used throughout, not equal to an empty string, makes a good test input on your own systems. Its evidence is plain, a sign-in or records that should not come back, and the query only reads. The lab's sign-in compares the password inside the query only so the operator has something to reach: a real sign-in stores a slow password hash and checks it in code, which the authentication guides in this library cover.
The username still reaches the query, and the lab's tests show a username sent as an object signing in as well.
JSON body injection: a value can be a string or an object
JSON is what makes this easy.
MDN describes JSON.parse() as returning the object, array, string, number, boolean or null value corresponding to the JSON text it is given. The parser hands your code whichever of those the client sent, and the flawed version never checked which one it got.
Frameworks say the same about the bodies they parse. Express's documentation for express.json() warns that because the shape of req.body is based on user-controlled input, all of its properties and values are untrusted and should be validated before trusting, and gives the example that a field may not be there or may not be a string.
Its strict option, on by default, accepts only arrays and objects, and it applies to the body as a whole, not to the values inside it.
In a Next.js Route Handler, which uses the Web Request API, request.json() resolves, in MDN's words, to anything that can be represented by JSON: an object, an array, a string, a number.
Next.js's data security guide makes the rule explicit: always validate input from the client, because it can be easily modified, and it names form data, URL parameters, headers and searchParams. It also says that by default an exported Server Action is reachable by a direct POST request, not only through your interface. The shape of your form is not what decides what the action receives.
The same object through a form or a query string
JSON is not the only way in.
A query string or a form body is text, but some parsers build objects from it. Express's query parser setting decides how req.query is filled: "simple" is based on Node's native querystring module, and "extended" is based on the qs library. The documented default is "extended" in Express 4 and "simple" in Express 5, and Express's migration guide confirms the change from extended to simple.
The qs README explains why that setting matters. qs lets a query string create nested objects by surrounding the names of sub-keys with square brackets, and it reads a bracketed name as a path into an object, where URLSearchParams and node:querystring read the same text as one flat name.
So under the extended parser, a parameter whose name ends with an operator in square brackets reaches req.query as an object holding that operator: the same shape the lab sends as JSON. Step 5 of the lab shows that form as a test case.
Forms follow the same pattern through express.urlencoded(). Its extended option chooses between the querystring library and qs. Express 5's documentation gives the default as false, its migration guide records that change, and the reference says that with extended set to true a value in req.body can be any type, where with false it is a string or an array.
Its own example, with extended set to true, turns a form field named user, with the sub-key name, into the nested object { user: { name: "Tobi" } }.
The simple parsers still need a type check. Node's documentation shows querystring.parse() turning a parameter that appears twice into an array, and Mongoose's query casting tutorial shows that when an array is given for a field that is not an array, Mongoose adds $in for you, so the query matches any of the values.
A check that each value is a string, not merely that it is not an object, covers the array and the object alike.
What a parameterised query means in a document database
In SQL, a parameterised query keeps the visitor's text out of the command by sending the values separately.
A document database query is already a structure: as MongoDB's FAQ puts it, the client builds a BSON object rather than a string. The risk to manage is not text breaking out of quotes. It is a value position in that object holding an operator instead of a value.
MongoDB's documentation gives a direct instruction for that. Under Security Implications on its $eq page, it says to always use the explicit form { field: { $eq: value } } with user-supplied input to avoid problems with maliciously formed queries.
Mongoose offers the same idea as an option. Its sanitizeFilter setting, false by default, wraps any nested object that has a property whose name starts with $ in a $eq, and its documentation's example turns a pwd of { $ne: null } into { $eq: { $ne: null } }.
Its trusted() function tells sanitizeFilter to skip an object, for a known query selector you want to use.
Neither replaces knowing what type each field should hold. The explicit form and sanitizeFilter still send whatever arrived as the value to compare, and they do nothing for a route that needs operators on purpose. ASVS 5.0 requirement 1.2.4, at Level 1, names NoSQL alongside SQL, HQL and Cypher when it asks that data selection or database queries use parameterised queries, ORMs or entity frameworks, or are otherwise protected from SQL injection and other database injection attacks. For a document database, the rest of this page is what that protection looks like in code.
OWASP's NoSQL cheat sheet points the same way. It says to use driver query objects rather than building query strings, not to accept raw JSON queries from clients, and to prefer high-level APIs that build queries safely, naming Mongoose among them. Its Java example passes the user's input to the driver's equality filter builder, Filters.eq, as a string value.
NoSQL injection prevention: check the shape of the request at the edge
Every defence above depends on one fact: what type each value is.
The durable fix is to establish that fact once, where the request enters your application and before any code reads a value. A sign-in route expects an object with exactly two fields, both strings of a sensible length. Write that down as a schema, check every request against it, and answer anything else with a 400. The query code then only ever sees strings.
ASVS 5.0 covers the same control. Its V2.2 Input Validation section says effective input validation controls enforce business or functional expectations around the type of data the application expects to receive, and that while schema validation is not explicitly mandated, it may be the most effective mechanism for full validation coverage of HTTP APIs or other interfaces that use JSON or XML.
Requirement 2.2.1, at Level 1, asks that input is validated to enforce business or functional expectations, either by positive validation against an allow list of values, patterns and ranges, or by comparing it with an expected structure and logical limits according to predefined rules; at Level 1 this can focus on input used to make specific business or security decisions, and from Level 2 it should apply to all input.
Requirement 2.2.2, also Level 1, asks that validation is enforced at a trusted service layer, and says client-side validation must not be relied upon as a security control.
The same section notes that validation does not remove or replace the need for correct encoding, parameterisation or sanitisation when the data is used in another component.
In the lab, the validated version does this with a few checks written out in plain JavaScript, since nothing is installed. The body must be an object, every expected field must be a string between one character and a set maximum, and any field the route does not expect is refused.
The password sent as an object gets a 400, password must be a string, and no query is sent. The same check also turns away an array, a number or a missing field, which no one had to think of in advance.
With a schema library the checks become declarations. Zod's documentation shows z.string() with .min() and .max() for a string's length, and z.strictObject() for an object schema that throws an error when unknown keys are found, where plain z.object() strips them from the parsed result.
Its .safeParse() returns either the parsed data or the error, so a route can answer 400 without a try and catch. Avoid Zod's coerced variants for these fields: its documentation shows z.coerce.string() calling String(input), which converts what it receives instead of rejecting it.
Next.js's forms guide suggests a schema validation library such as Zod or Valibot for server-side validation, with safeParse used to return early when the data is invalid.
One shortcut turns up in code: turning the body back into JSON text and rejecting it if a quote mark is followed by a dollar sign. OWASP's NoSQL cheat sheet calls that check a denylist, not an operator allowlist.
It also rejects ordinary string values that begin with a dollar sign, and it does not validate allowed fields or their types. The cheat sheet's advice is field-specific validation before queries are built.
Some routes accept operators by design: a list screen with filters, a report builder, an API for a partner. A schema that demands strings would take the feature away. The defence there is an allow-list for each route: which fields may be filtered, which operators each field allows, and what type each operand must be, with everything else refused.
OWASP's NoSQL cheat sheet says to disallow client-controlled query operators, naming $where, $regex and $expr, unless they are strictly required and validated, and its list of things to do includes validating and allow-listing the fields a user supplies.
The lab's allow-listed version gives each route a rule set. Sign-in and tracking allow plain equality on strings only, so the object password is refused with $ne is not allowed on password. The repairs search lets the signed-in customer filter by status, with equality or $in, and by days in the workshop, with $gte and $lte.
In the flawed version, the search sets the customer first and copies the request's filter over it, so a filter that sends the customer field as { $ne: "" } replaces it and the response lists all four repairs.
The allow-listed version refuses that field, customer is not a field this route filters on, and adds the signed-in customer after the request's filter, so nothing in the request can replace it.
Who may see which records is the subject of the broken access control guide; the point here is that the route, not the client, decides the fields and operators.
Mongoose's schemas guide puts it briefly: in general, it does not recommend passing user-defined objects as query filters. Its example of what not to do passes req.query straight to find(), and its alternative names each field and sets sanitizeFilter. An allow-list also has to say what is required.
The lab's sign-in rules mark both fields as required, because a filter with the password field left out would match on the username alone. A request that sets fields it should not on a write, rather than a filter, is mass assignment, which has its own guide.
The third defence works at the data layer. Before building a filter, the lab's cast version converts each value to the type its field holds: a string stays a string, a number, true or false becomes text, and anything else is refused with a CastError that goes to the server log while the client gets a plain 400.
Casting protects every caller of the data layer, including code paths that skipped validation, which makes it a useful backstop. It converts some values rather than rejecting them, so it does not replace the schema at the edge.
Do not assume an object-document mapper (ODM) does this for you. Mongoose's query casting tutorial shows it casting the filter to match your schema when the query runs: in its example the value of an age $gt condition, given as the string 50, is cast to a number, and the $gt operator stays in the filter.
A value it cannot cast throws a CastError. In that example the $gt operator stays in the filter and only its value is cast.
The cast that protects a field is one your code applies to the whole value, or the sanitizeFilter option described above.
Mongoose's strictQuery option needs care as well. It is false by default, and the schemas guide sets out the three settings for filter paths that are not in the schema: false leaves the path in the filter as it is and does not cast its value, true silently removes the path, so the query may match more documents than intended, and 'throw' throws a StrictModeError instead.
The guide's own example of the true setting strips the only path in a filter and matches every document.
Running the NoSQL injection lab
The lab is an illustration: an invented bike repair workshop with three invented customers and four invented repairs. collection.mjs stands in for a document database.
It holds the records in memory, understands plain equality and five comparison operators, and records every filter it receives. That proves what your own code passes to the database layer; what a real database does with an operator is set out in its own documentation, quoted above.
The lab imports only node:http, node:test and node:assert/strict and installs no packages. It is for learning and for testing code you own. Sending operator input to a system you do not own, without the owner's written authority, is not something this page helps with.
It was written and run on Node.js 26.0.0, and every output in it comes from that run; test timings will differ on your machine. The Node.js documentation marks node:test stable from version 20.0.0, and says fetch() is no longer behind the --experimental-fetch flag from 18.0.0 and no longer experimental from 21.0.0, so the lab needs Node.js 20.0.0 or later.
- Make an empty folder, save the four files into it with the names shown, and open a terminal there.
- Run node lab.mjs. It starts a web server on 127.0.0.1, on a port the operating system assigns, sends each request to every version that offers the route, and prints the body sent, the filter each version passed to the data layer, any server log line and the response. Then it stops.
- Run node regression.test.mjs flawed. Four of its eight tests fail: a password or a username sent as an object signs Ava in, and a tracking code or a customer field sent as an object returns all four repairs.
- Run node regression.test.mjs validated, then allowlisted, then cast. Every test passes. With no argument the file tests the validated version, so node --test, which by default runs files whose names end in .test.mjs, among other patterns, can run it in a pipeline, and a failing test sets the process exit code to 1.
Pointing the regression tests at your own code
Keep the cases and change what they call. signedInAs should call your real sign-in handler or data access function with a test account, and the tracking and search calls should reach your real lookups, against a test database that holds records for at least two customers.
The ordinary cases check that each route still works. Each object case fails if a value of the wrong type can change what a lookup matches. Add an object case for every field that reaches a filter, and for a route that reads a query string or a form under a parser that builds objects, send the marker in that encoding too, as step 5 of the lab shows.
What to check in a Next.js or Node.js application that uses an ODM
Most of these checks are searches you can run over your own code.
Each names the documentation behind it. The Next.js security guide in this library covers that framework's other entry points.
- Filters built from request objects. Search for find(), findOne() and the update and delete calls that take a filter, wherever they receive req.body, req.query, a Server Action argument or the result of request.json() directly, or an object copied or spread from one of them. Mongoose's schemas guide shows find(req.query) as the pattern not to use.
- Fields copied without a type check. A filter such as { email: body.email } is the flawed lab version. Each such field needs a schema check at the edge or a cast before the query, in line with the NoSQL cheat sheet's advice to validate the expected scalar type.
- Mongoose settings. Check whether sanitizeFilter is turned on, with mongoose.set() or per query with setOptions(), since it is false by default. Search for trusted(), which tells sanitizeFilter to skip an object. Check strictQuery, false by default, where true silently removes a filter path that is not in the schema, so the query may match more documents than intended.
- Express version and parsers. Check which major version of Express you run, and whether the query parser setting or express.urlencoded() uses the extended, qs-based parser, which builds nested objects from square brackets in parameter names.
- Next.js entry points. Route Handlers, Server Actions and server components that read searchParams each take client input, which Next.js's data security guide says to always validate, and by default an exported Server Action is reachable by a direct POST. The guide recommends a Data Access Layer for new projects, and keeping database calls inside it gives the casts one place to live.
- Server-side JavaScript. Search for $where, $function, $accumulator and mapReduce. MongoDB documents how to disable server-side JavaScript entirely, and OWASP's NoSQL cheat sheet advises turning off or restricting features that execute code on the server.
- The database account. OWASP's NoSQL cheat sheet says to use least privilege for service accounts, separate users for admin, backup, read-only and application work, and not to use root or admin accounts for application connections.
- Regression tests. Give each route that filters on request values a test like the lab's and run it in the pipeline that deploys the app. The NoSQL cheat sheet lists automating security testing in CI/CD pipelines among the things to do.
NoSQL injection testing on your own application
OWASP's Web Security Testing Guide v4.2 covers this in Testing for NoSQL Injection, numbered 4.7.5.6 under its SQL injection test (WSTG-INPV-05); the NoSQL page shows no separate test ID.
It says there are over 150 NoSQL databases, that example injection code will not apply across all of them, and that anyone testing needs to become familiar with the syntax, data model and underlying programming language. Its examples use MongoDB APIs. It also makes a point worth keeping: as with other injection testing, one does not need to fully exploit the vulnerability to demonstrate a problem.
On your own copy, the lab gives the method.
- Work on a local or staging copy with invented records for at least two customers, not on production data.
- List every field that reaches a filter: sign-in, password reset and invitation lookups, record lookups by code or ID, search and list filters, and fields in query strings and forms as well as JSON bodies.
- For each field, send the ordinary value, then the same request with that one value replaced by the not-equal-to-empty marker, changing one field at a time. For a query string or form route under an extended parser, send the marker in that encoding as well.
- Compare status codes, whether a sign-in succeeded, the number of records returned, and the filter your application or database log recorded. A sign-in without the password, or more records for the marker than for the real value, means the value reached the filter as an operator.
- Stop at that finding. A value of the wrong type changing what the query asks is the whole result; the fix and a regression test come next.
- Read the code as well as sending requests. OWASP's Injection Prevention Cheat Sheet says injection flaws are easy to discover when examining code, but more difficult via testing, and the OWASP Top 10:2025 says detection is best achieved by combining source code review with automated testing, including fuzzing, of all parameters, headers, URL, cookies, JSON, SOAP and XML data inputs.
Only on systems you own or are authorised to test
All of this is for systems you own or are authorised in writing to test. Sending the marker to someone else's website or API without that authority is not something this page helps with.
Where an outside review or test fits
The lab tests the routes you know about.
A review looks for the ones you do not. Clever Ops reviews code for applications such as Next.js, React and Node with read-only access to the repository, and a secure code review follows the paths in scope, looking at untrusted input along the way. Code findings are confirmed against a running build where the scope allows, and the report marks any that rest on the code alone.
A web application and API penetration test exercises the running application, and read-only code access to named areas can be added to confirm how a control is enforced. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
It is a way of changing what a database query asks by sending a different kind of value. If an application copies a value from a request into a filter for a database such as MongoDB, an object such as { "$ne": "" } where the code expected text turns "this password" into "any password that is not empty". MITRE catalogues the weakness as CWE-943 and lists NoSQL injection as an alternate term.
MongoDB's FAQ says traditional SQL injection is not a problem, because a query is built as a BSON object rather than a string. Operator injection is a different route: OWASP's NoSQL Security Cheat Sheet notes that a query object does not prevent it when an untrusted value is itself an object. MongoDB's FAQ also lists operations, such as $where, that run JavaScript on the server and need care to keep users from submitting malicious JavaScript.
A request supplies a query operator, such as $ne or $in, where the code expected a plain value, and the database evaluates the operator instead of comparing the value. In this page's lab, a password sent as { "$ne": "" } signs in without the password, and a tracking code sent the same way returns every customer's repairs.
Check the shape of each request where it enters your application, so every field that reaches a filter has the type you expect, usually a string, and refuse anything else. For routes that take a filter on purpose, allow-list the fields, operators and value types. Cast values at the data layer as a backstop, and disable server-side JavaScript if you do not use it. The lab shows each fix with tests that fail without it.
Not by default. Mongoose's sanitizeFilter option, which wraps nested objects that have a property whose name starts with $ in a $eq, is false by default, and its query casting changes the type of an operator's value while keeping the operator, as its tutorial's $gt example shows. Its schemas guide says that, in general, it does not recommend passing user-defined objects as query filters. Validate request fields before they reach a Mongoose query.
Yes, depending on the parser. Express's extended query parser, the documented default in Express 4, is based on qs, which builds nested objects from square brackets in parameter names. Express 5 defaults to the simple parser, which is based on Node's querystring, and Node documents querystring.parse() turning a repeated parameter into an array. A check that each value is a string covers all of these.
On a copy you own, list every field that reaches a filter, then send each one an ordinary value and the same request with that value replaced by an object such as { "$ne": "" }, one field at a time. A sign-in without the password, or extra records, means the value reached the query as an operator. OWASP's WSTG v4.2 covers this in Testing for NoSQL Injection. Test only systems you own or have written authority to test.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.