On 16 November 2026, the Mongoose team released Mongoose 9.12.2 and 8.24.10 with security hardening for two options many Node.js apps rely on to block NoSQL injection: sanitizeFilter and sanitizeProjection. If you pass any user input into Mongoose queries, and almost every Express, Fastify or NestJS API does, you should upgrade and check how you use these options. This tutorial explains the bypasses that were closed, shows safe query patterns, and gives you tests to prove your app is protected.

Sources: the 9.12.2 and 8.24.10 release notes, the fix commits in the Mongoose repository, and the Mongoose docs.

What was fixed

The changelog for both versions lists the same two security items:

  1. sanitizeFilter now rejects any top-level field that starts with $. Before the fix, it blocked a short deny-list ($where, $expr, $jsonSchema, $text). Attackers could get around it with MongoDB internal operators such as $_internalSchemaXor to build conditions on fields they shouldn’t be able to probe, for example running a regex against a password hash. The new rule is simple: apart from $and, $or and $nor (which are searched recursively), any $-prefixed top-level key throws "<key> is not allowed with sanitizeFilter" unless you explicitly mark it as trusted.
  2. sanitizeProjection was hardened. Projection values that are objects are now reduced to 1 unless they are a safe operator: $meta: 'textScore', $elemMatch, or a numeric $slice. Expressions such as { name: { $concat: ['$password'] } } and $slice: ['$otherArray', 1] can read other fields, so they are now neutralised. A __proto__ key in select() is stripped too.

Step 1: Upgrade

# Mongoose 9
npm install mongoose@^9.12.2

# Still on Mongoose 8
npm install mongoose@^8.24.10

npm ls mongoose

Mongoose 9.12.2 also contains bug fixes, such as BigInt handling in addToSet() and stricter casting in replaceOne(). Check the release notes if you rely on those paths.

Step 2: Understand the attack you’re defending against

Query selector injection happens when you pass request data straight into a filter. A JSON body like this:

{ "email": "[email protected]", "password": { "$ne": null } }

turns find({ email, password }) into “any user with that email and a non-null password”. That is a login bypass.

sanitizeFilter defends against this by wrapping nested objects in $eq, so { $ne: null } becomes a literal value to compare against instead of an operator.

Step 3: Turn on sanitizeFilter globally

The safest setup is to enable it for every query, early in your app, before you define models:

// db.js
import mongoose from 'mongoose';

mongoose.set('sanitizeFilter', true);
mongoose.set('sanitizeProjection', true);

await mongoose.connect(process.env.MONGODB_URI);
export default mongoose;

You can also enable it per query:

const user = await User.findOne({ email: req.body.email })
  .setOptions({ sanitizeFilter: true });

Even with sanitising on, pick fields explicitly instead of passing whole objects:

// ❌ Never do this
const users = await User.find(req.query);

// ✅ Do this
const users = await User.find({
  name: req.query.name,
  city: req.query.city,
}).setOptions({ sanitizeFilter: true });

Step 4: Use mongoose.trusted() for operators you write yourself

With sanitising on, your own operators get wrapped too. Mark the ones you wrote, never user input, with mongoose.trusted():

import mongoose from 'mongoose';

// The developer chose $gte, so it is trusted. The user only supplies a number.
const minAge = Number.parseInt(req.query.minAge ?? '18', 10);

const adults = await User.find({
  status: req.query.status,                     // user input: sanitized
  age: mongoose.trusted({ $gte: minAge }),      // our operator: allowed
});

After the fix, this matters for top-level operators too. A query that adds $comment or another $-prefixed top-level key while sanitizeFilter is on now throws. If you really need one, wrap the value in mongoose.trusted():

await Order.find({
  customerId: req.user.id,
  $comment: mongoose.trusted('orders-list-endpoint'),
});

Step 5: Protect select: false fields with sanitizeProjection

MongoDB treats some projection values as expressions, and they can leak hidden fields. The Mongoose docs show this example:

const userSchema = new mongoose.Schema({
  name: String,
  password: { type: String, select: false },
});
const User = mongoose.model('User', userSchema);

// Without sanitizeProjection, a '$password' string can copy the hidden field
let doc = await User.findOne().select({ name: '$password' });

// With sanitizeProjection, values are forced to numbers: doc.name is the real name
doc = await User.findOne().sanitizeProjection(true).select({ name: '$password' });

// It also blocks '+password' from pulling in select:false fields
doc = await User.findOne().sanitizeProjection(true).select('+password');

The new release extends this protection to object expressions. If your API lets clients choose fields (?fields=name,email), build the projection yourself from an allow-list:

const ALLOWED = new Set(['name', 'email', 'createdAt']);

function buildProjection(fieldsParam = '') {
  const projection = {};
  for (const f of fieldsParam.split(',')) {
    if (ALLOWED.has(f.trim())) projection[f.trim()] = 1;
  }
  return projection;
}

const users = await User.find({})
  .select(buildProjection(req.query.fields))
  .sanitizeProjection(true);

Step 6: Prove it with a test

Add regression tests so a future refactor can’t silently remove the protection. Here is an example with Node’s built-in test runner and an in-memory or test database:

// test/injection.test.js
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import mongoose from 'mongoose';

let User;

before(async () => {
  mongoose.set('sanitizeFilter', true);
  await mongoose.connect(process.env.MONGODB_TEST_URI);
  User = mongoose.model('User', new mongoose.Schema({
    email: String,
    password: { type: String, select: false },
  }));
  await User.create({ email: '[email protected]', password: 'hash' });
});

after(async () => {
  await mongoose.connection.dropDatabase();
  await mongoose.disconnect();
});

test('nested operators from user input are neutralised', async () => {
  const body = { email: '[email protected]', password: { $ne: null } };
  // Sanitized, the object is compared literally (or fails to cast), so no user leaks out
  const found = await User.findOne(body).catch(() => null);
  assert.equal(found, null);
});

test('internal top-level operators are rejected', async () => {
  const body = { $_internalSchemaXor: [{ password: { $regex: '^h' } }, { $alwaysFalse: 1 }] };
  await assert.rejects(async () => User.find(body), /not allowed with sanitizeFilter/);
});

Run it with:

MONGODB_TEST_URI="mongodb://127.0.0.1:27017/app_test" node --test

The second test fails on older Mongoose versions, which is exactly what you want to catch in CI.

Step 7: Add validation in front of Mongoose

Sanitising is a safety net, not your only layer. Validate request shapes at the edge so objects never reach a field that expects a string:

import { z } from 'zod';

const Login = z.object({
  email: z.string().email(),
  password: z.string().min(8),
});

app.post('/login', async (req, res) => {
  const parsed = Login.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ error: 'Invalid input' });

  const user = await User.findOne({ email: parsed.data.email }).select('+password');
  // compare parsed.data.password with the stored hash using bcrypt/argon2
});

Version support reminder

According to Mongoose’s version support page, Mongoose 6 reaches end of life on 1 February 2027 and Mongoose 7 on 1 November 2027. After those dates they won’t get security fixes. If you’re on 6.x or 7.x, plan your move to 8 or 9 now.

Takeaway

Upgrade to Mongoose 9.12.2 or 8.24.10, turn on sanitizeFilter and sanitizeProjection globally, use mongoose.trusted() only for operators you write yourself, and add an injection test to CI. Together with schema validation at the edge, that closes the most common NoSQL injection paths in Node.js APIs.