You did the responsible thing. The user model has password: { type: String, select: false }, you checked GET /users/me, and the hash was gone. Box ticked.
Then, a few weeks later, someone adds a public blog feed. It populates the author so the frontend can show a name next to each post. And now every anonymous visitor gets the author’s email, their roles array, maybe an isVerified flag and a lastLoginIp you forgot you were storing. Nobody wrote a bug. Everyone just did the obvious thing in their own file.
const userSchema = new Schema({
name: String,
email: String,
roles: [String],
password: { type: String, select: false },
});
app.get('/api/posts', async (req, res) => {
const posts = await Post.find({ status: 'published' })
.populate('author');
res.json(posts);
});
// author: { name, email, roles, ... } password is gone, the rest is notOWASP has a name for this. API3:2023 Broken Object Property Level Authorization covers two sides of the same mistake: the API exposes properties the user should not read, or it lets the user change properties they should not touch. This post is about both, in Mongoose, because that is where I keep seeing it.
The usual defenses, and where each one fails
select: false on the schema. The Mongoose SchemaType docs describe it as excluding a path by default, overridable at the query level. It does apply to populated documents too. I checked the Mongoose source rather than trusting memory: populate loads the referenced docs with a normal find() on the target model, so the schema defaults run. The catch is that it is opt-in per field. It protects the one field you remembered. Email and roles were never marked, so they ride along.
A toJSON transform. Nice and central, until someone adds .lean() for speed. Lean returns plain objects, so your document transform never runs. Same problem with anything that serializes without going through the document.
.select('-password') in the route. Works for that route. The next route is written by someone else on a Friday.
Hand-written DTOs. Honestly the safest of the lot, because you list what goes out. It just tends to drift. The DTO for /users/:id is careful, the one hiding inside the posts controller is a spread operator.
Leaks through relations
Relations are where single-model thinking breaks. Three places to look:
- populate. The populate docs show how to narrow it with a second argument,
populate('author', 'name'). Without that, you get every field the target schema does not exclude. - Aggregation
$lookup. An aggregate pipeline goes straight to MongoDB. Your schema’sselect: falseand yourtoJSONtransform are not part of that trip, so the joined user comes back with everything, password hash included, unless you add a$projectyourself. - Embedded copies. Someone denormalized
author: { _id, name, email }into each post two years ago for a dashboard. The user model got stricter since. The copies did not.
The other direction: mass assignment
Reading too much is half of it. Writing too much is the other half. User.create(req.body) and User.updateOne({ _id }, req.body) are short and pleasant, and Mongoose strict mode will drop fields that are not in your schema. But roles, owner and verified are in your schema. That is the whole point of them. So PATCH /users/me with {"roles": ["admin"]} just works, and OWASP’s advice applies word for word: allow changes only to the properties the client should update.
I wrote a whole post on testing your API as every role, and this is exactly the kind of thing those tests catch: sign in as a normal user, try to promote yourself, expect a refusal.
Fixing it by hand
You do not need a framework for this. You need two lists per model, kept in one place, and used everywhere:
// models/user.visibility.js
export const userPublic = ['_id', 'name', 'avatarUrl'];
export const userWritable = ['name', 'avatarUrl'];
export const pick = (obj, keys) =>
Object.fromEntries(keys.filter(k => k in obj).map(k => [k, obj[k]]));
// every response, populated docs too (posts from .lean())
res.json(posts.map(p => ({ ...p, author: pick(p.author, userPublic) })));
// in every write: reject, don't silently ignore
const extra = Object.keys(req.body).filter(k => !userWritable.includes(k));
if (extra.length) return res.status(422).json({ unknown: extra });
// and a test that fails loudly
assert.equal(body.data[0].author.email, undefined);The allowlist matters more than the exact code. A denylist (-password) only protects what you thought of. An allowlist protects you from the field someone adds next month. Rejecting unknown input with an error, instead of quietly dropping it, also tells the client developer what went wrong, which saves you a support thread.
Then add the absence tests. One per sensitive field, for the anonymous route and the populated route. They are boring to write and they are the only thing that stays true after a refactor. And while you are in there, do the same for query input. I covered that side in stop passing req.query straight into MongoDB.
How CalmAPI handles it
Disclosure first: I built CalmAPI, our open source Express and MongoDB framework. The 2.0 line is still in beta (calmapi.dev says 2.0.0-beta.1, and npm already has 2.0.0-beta.2 on the next tag). You start a project with npm create calmapi@latest my-api, and it needs Node.js 22.12 or later plus MongoDB.
The idea is the same two lists, written next to each field. This is the user resource that ships in the api template of the 2.0.0-beta.2 package, plus one line from its posts test:
// app/resources/user/user.resource.js
email: f.email().required().unique().immutable().filterable().visibleTo('owner | admin'),
password: f.password().required(),
roles: f.array(f.enum(['user', 'admin'])).default(['user']).writableBy('admin').visibleTo('owner | admin').filterable(),
status: f.enum(['active', 'disabled']).default('active').writableBy('admin').filterable(),
// test/posts.test.js
const list = await t.get('/posts?include=author');
assert.equal(list.body.data[0].author.email, undefined, 'author email is private');Per the Resources docs, the modifiers are .hidden() (never returned, never accepted), .writeOnly() (accepted, never returned), .readOnly() (returned, never accepted), .immutable() (create only), .writableBy(policy) and .visibleTo(policy), plus f.ref('user').owner() for an owner field that is set from the signed-in user. A populated reference is serialized with the target resource’s own rules for the current viewer, which is the exact gap from the top of this post. Send a hidden, read-only or undeclared field in a body and you get a 422 with code VALIDATION_ERROR and a details entry per field, such as “Is read-only” or “Unknown field”. There is also .encrypted() for secrets at rest, which the docs are careful to say protects storage, not access, so pair it with .visibleTo() or .hidden().
The habit, not the tool
Decide what each model may show and what each client may write, write it down once, and test that the forbidden fields are really absent, especially on routes that pull in other models. Use whatever you like, the habit matters more than the tool. If you want to see what else we keep in the open, it is on our open source page.

