Search code examples
mongodbmongodb-atlaschangestream

Change Stream throwing Error “Unauthorised to execute command”


We have recently migrated our data from Azure Cosmos to MongoDb Atlas. I have a node.js server that watches collections. This code was working perfectly with Azure Cosmos but is throwing the following error when switching out the URL to MongoDB Atlas:

const collection = db.collection(collectionName);
const changeStream = collection.watch([pipeline], { fullDocument: "updateLookup" });
 //listening to changes on the collection with roomId
 changeStream.on('change', (change) => { ... }
Cluster details:
VERSION 6.0.13
CLUSTER TIER M50 (NVMe SSD)
TYPE Replica Set - 3 nodes

connection URL format: “mongodb+srv://user:[email protected]/dbName/?&retryWrites=true&w=majority”

I have also granted nearly all permissions on the db (all collections) including find and changeStream from the MongoDB Atlas console.

The full error:

MongoError: not authorized on {dbName} to execute command { aggregate: "system.views", pipeline: [ { $changeStream: { fullDocument: "updateLookup" } }, { $match: { operationType: { $in: [ "insert", "update", "replace" ] } } }, { $project: { _id: 1, fullDocument: 1, ns: 1, documentKey: 1 } } ], cursor: {}, lsid: { id: UUID("") }, $clusterTime: { clusterTime: Timestamp(1707836562, 4), } }, $db: "dbName" }

I have already tried

updating and downgrading the node.js driver changing the URL connection string format to other variants suggested on Stack Overflow. Would really appreciate any kind of help on how to even troubleshoot this!!!


Solution

  • From the docmentation, the built-in read role does not provide read access to system collections.

    read

    Provides the ability to read data on all non-system collections and the system.js collection.

    Did you really intent to monitor the system collections as well?

    If not, filter the list of collections to exclude them before starting the changestreams.

    If you did, you will need to create a custom role that explicitly grants read access on each system collection.