13
MongoDBERRORNotableAuthorizationHIGH confidence

Not authorized to perform an action

What this means

This error occurs when an authenticated user attempts to perform an operation they do not have sufficient privileges for. It signifies a permissions issue, where the user's assigned roles do not grant the required access for the action on the target resource.

Why it happens
  1. 1Attempting to read from a collection when the user only has write permissions
  2. 2Trying to create an index without a role that grants `createIndex` privileges
  3. 3Executing an administrative command (e.g., `listShards`) without the necessary cluster-level role
  4. 4Connecting to the wrong database where the user has no roles assigned
How to reproduce

A user with a read-only role attempts to insert a document into a collection.

trigger — this will error
trigger — this will error
// User 'reader' has role 'read' on 'testDB'.
// As the 'reader' user:
use testDB
db.inventory.insertOne({ item: "book", qty: 1 })

expected output

MongoServerError: not authorized on testDB to execute command { insert: "inventory", ... }

Fix 1

Grant the Necessary Role

WHEN The user legitimately needs to perform the action.

Grant the Necessary Role
// As an administrative user:
use testDB
db.grantRolesToUser("reader", [{ role: "readWrite", db: "testDB" }])

Why this works

Modify the user's roles to include the permissions required for the failed operation. Always follow the principle of least privilege.

Fix 2

Review and Correct Application Logic

WHEN The application is attempting an action it should not be performing.

Review and Correct Application Logic
// Application logic should be reviewed to ensure this user
// is not supposed to be writing data.
console.log("User does not have write access. Aborting operation.");

Why this works

Sometimes the error correctly highlights a flaw in application logic. Instead of changing permissions, fix the application to prevent it from attempting unauthorized actions.

What not to do

Assign powerful roles like `dbAdmin` or `root` as a quick fix

This is a significant security risk. Granting excessive permissions bypasses security controls and exposes the database to accidental or malicious damage.

Sources
Official documentation ↗

mongodb/mongo src/mongo/base/error_codes.yml

Role-Based Access Control (RBAC)

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MongoDB errors