MongoDBError: Unauthorized access attempt for [action] operation by the user is prohibited

I've been struggling with this error for quite some time now, attempting all the recommendations on this forum without success. My goal is to develop a website where users can register and their credentials are saved in a database. Below is a snippet of my JavaScript code that connects to my Atlas database:

const { MongoClient } = require("mongodb");


const dbURI = 'mongodb+srv://gettingstarted.owxpopb.mongodb.net/GettingStarted';

mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true });

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
  console.log('Connected to MongoDB Atlas');
});

Upon checking the command line, it shows 'connected to MongoDB Atlas' confirming successful connection. This is my user schema description:

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String,
  numberOfTickets: {
    type: Number,
    default: 0
  }
});

However, when I attempt to save or verify a user's information against the existing database using the following code:

User.findOne({ email: newUser.email }, (err, existingUser) => {
    if (err) {
      // Handle error
      console.error(err);
      return res.status(500).send({ message: 'Internal server error' });
    }

    if (existingUser) {
      // A user with the same email address already exists
      return res.status(409).send({ message: 'Email address already registered' });
    }

    // If we reach here, it means the user details are not already in the database
    // You can proceed with saving the user to the database
    const newUser = new User(userSchema);
    newUser.save((err, savedUser) => {
      if (err) {
        // Handle error
        console.error(err);
        return res.status(500).send({ message: 'Internal server error' });
      } else{
        res.render("home");
      }
      // User saved successfully
      return res.status(200).send(savedUser);
    });
  });

It returns a MongoServerError: user is not allowed to do action [find] on [GettingStarted.users]. Despite trying various solutions like updating MongoDB security access to readWrite, giving myself admin rights, verifying node.js driver compatibility, the issue persists. Can anyone provide assistance?

I have checked existing solutions on this platform, but none have resolved the problem.

Answer №1

The reason for my issue was that I forgot to assign a role to the user in mongoDB. It's crucial to set the user role as 'atlasAdmin'.

I encountered a similar problem where my mongoDB was connected and displayed on the console, but I couldn't create a user.

This was the error message I received:

MongoServerError: user is not allowed to do action [find]

To resolve this, I followed the solution provided in this link.

Here are the steps I took:

  1. Open your mongoDB
  2. Access Database access
  3. Click on 'edit' next to the user's profile
  4. Expand the built-in user roles section
  5. Select 'atlasAdmin' from the roles dropdown menu

Click here to Edit

Expand Built-in Role

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to resolve the issue of BrowserWindow not being recognized as a constructor when trying to create a child window within the Electron

Currently, I am utilizing electron to construct an application with two windows. In my attempt to open a second window from the renderer process, I have implemented the following code snippet: const electron = require('electron'); const BrowserW ...

Apply a custom filter to ng-repeat results

Asking for advice on how to iterate over an array using ng-repeat and filter the contained objects based on a function property. Find more details in this Plunker link. Let's say we have an object like this: vm.show1 = function(){ return true; }; ...

Struggling to make a JavaScript program that sums up odd numbers

Let's tackle this challenge: Your task is to create a program that adds up all the odd numbers between 1 and the number provided by the user. For instance, if the user inputs 7, the program should calculate 1 + 3 + 5 + 7. The result of this calculati ...

Utilizing jQuery to reset a toggle feature

I have created a custom clickToggle function, but I am facing an issue with it. The function currently toggles between opening and closing a div based on the clicks. The problem arises when the div is closed by clicking outside of it without activating th ...

What is the best way to transfer data to a component that is not directly related

I am looking to showcase an image, title, and description for a specific recipe that I select. Here is my setup using ItemSwiper (parent): <template> <Slide v-for="recipe in storeRecipe.data" :key="recipe.rec ...

Issue with Nextjs 13: Unable to locate 'src/app/dashboard/layout.tsx' (deleted optional layout)

Deciding to start a fresh Nextjs 13.4.5 project, I set up an app directory. Within the app directory, I created a new dashboard directory and added page and layout components. Everything seemed to be functioning smoothly with two layout components - one i ...

Ways to conceal a button using Javascript

Due to my limited JavaScript experience, I am struggling with understanding the event flow. This was written in haste, and further editing may be needed. I am working on creating a stack of cards (Bootstrap cards) along with a load button. To keep it inde ...

Exploring a React JS option for filtering repeated elements, as an alternative to Angular

While using Angular JS, I came across the 'filter' option within ng-repeat which is useful for live search. Here's an example: <div ng-repeat="std in stdData | filter:search"> <!-- Std Items go here. --> </div> &l ...

I am facing an issue with my middleware setup. It functions correctly when I include it in my app.js file, but for some reason, it does not work when I add it to my server.js file

Displayed below is my App.js information: const express = require("express"); const dotenv = require("dotenv"); const movieRouter = require("./routes/movieRoutes"); const userRouter = require("./routes/userRoutes"); ...

Using regex to pick out every instance of zero that comes before a numerical value

I am currently utilizing PowerRename, a tool that allows for regex usage to select portions of filenames for replacement. My goal is to tidy up some filenames by removing the preceding zeroes before a number in the file name (replacing them with nothing). ...

When using JavaScript, I have noticed that my incremental pattern is 1, 3, 6, and 10

I am currently using a file upload script known as Simple Photo Manager. Whenever I upload multiple images and wish to delete some of them, I find myself in need of creating a variable called numDeleted (which basically represents the number of images dele ...

The React file fails to render properly in the browser when initiated

I downloaded a Bootstrap template for my project, but when I run the script in the browser, nothing shows up. Can anyone help me identify the issue in this code? I was expecting to see the output on my localhost. In the home.jsx file, I had to remove ...

Arranging a nested JSON array directly

Below is the structure of my JSON data : Root |- cells [] |-Individual cells with the following |- Facts (Object) |- Measures (Object) |- Key value pairs |- other valu ...

What could be the reason for my function not being executed in this particular scenario with my calculator HTML code?

Memory = "0"; Current = "0"; Operation = 0; MAXLENGTH = 30; alert("yea"); function AddDigit(digit) { alert("yea"); if (Current.length > MAXLENGTH) { Current = "Aargh! Too long"; } else { if (eval(Current) == 0) { Current = dig; ...

EJS selectively displaying certain elements from an object

This particular issue has been baffling me. I have been passing an object into an ejs template and when I output that object, everything appears as expected: { _id: 5504a5e7ff67ac473dd7655c, code: 'GB', name: 'United Kingdom', slug: & ...

Choosing HTML elements within nested DIV tags

In the process of creating a Hangman-style game using javascript/jQuery, I encountered an issue with selecting HTML content from virtual keyboard keys : <div class="square keyboard"> <div class="content"> <div class="table"> ...

Error Occurred: ngRepeat directive encountered an invalid expression while attempting to render the

HTML <tr ng-repeat="sale as examples"> <td class="text-right"> @{{sale.sales_person}}</td> <td class="text-right"> @{{sale.sales_total}}</td> <td class="text-right"> @{{sale.sales_target_amount}}</td> ...

What is the best way to eliminate specific elements from an array of objects in MongoDB aggregate based on a condition?

I have a database of documents called ChatRooms stored in MongoDB with the following structure: { _id: ObjectId('4654'), messages: [ { user: ObjectId('1234'), sentAt: ISODate('2022-03-01T00:00:00.000Z') ...

Revamp user profile pages with Mongoose and Express.js

I've been working on a personal project that involves allowing users to update their profile, but I'm facing some difficulties with this functionality. Here's what I've done so far: <form action="/users/doctor-profil ...

The status of Mongodb has encountered a failure following the modification of the .conf

My goal is to enhance security by creating a user in the admin database. I successfully created the user and then proceeded to edit the MongoDB configuration file. However, I encountered an issue while attempting to connect as I was unable to connect wit ...