Connect from Node.js

I would like to connect to the M121 sharded cluster from Node.js to make doing the labs and homeworks easier and require less retyping.

I have tried this (in attempts to mimic the client connection command)

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://,,";

let options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,

  // added
  auth: {
    user: "m121",
    password: "aggregations"
  ssl: true,
  authSource: "admin"

module.exports = new MongoClient(uri, options);

As well as a similar attempt where the options are instead specified in the connection string: “mongodb://,,

The client is loaded into other modules and used like so:

let client = require('./client.js');

async function query() {
  await client.connect();

  const collection = client.db('aggregrations').collection('air_airlines');

  const aggregation = [
    { $match: {} }, // match everything
    // { $group: { _id: "$room_type" } },
    // { $project: { _id: 1 }}

  const result = collection.aggregate( aggregation );
  // ...

  await client.close();

In either case, I get an error like so when trying to perform queries / aggregations on the database:

(node:19351) UnhandledPromiseRejectionWarning: MongoError: not authorized on aggregrations to execute command { aggregate: "air_airlines", pipeline: [ { $match: {} } ], cursor: {}, ls...

Any ideas what’s going on? My query code works on other databases, for example the databases in the cluster made in m001 or local databases.

async functions need try catch block for error handling.

You have the wrong collection. This user has only access to the aggregations database. You are trying to access aggregrations. You have a typo.

1 Like

Oh no, just an embarrassing typo. Well, that was the issue. Thanks!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.