Not authorized to perform an action
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.
- 1Attempting to read from a collection when the user only has write permissions
- 2Trying to create an index without a role that grants `createIndex` privileges
- 3Executing an administrative command (e.g., `listShards`) without the necessary cluster-level role
- 4Connecting to the wrong database where the user has no roles assigned
A user with a read-only role attempts to insert a document into a collection.
// 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.
// 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.
// 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.
✕ 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.
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