Encountered error 8000 while attempting to add a new user in mongodb

Hello everyone, I want to start by saying that I am new to MongoDB and I am encountering some challenges due to terminology blind spots. Currently, I am working on creating a simple authentication endpoint. Everything seems to be in order and error-free as the connection to the database is successful. However, when I try to create a new user using Postman, I keep getting a 500 error message:

{
    "message": "Error creating user",
    "error": {
        "ok": 0,
        "code": 8000,
        "codeName": "AtlasError",
        "name": "MongoError"
    }
}

I have tried searching for solutions online (Google, MongoDB docs) but have not been able to find much information. I would appreciate any guidance or direction on where to look. The issue may lie in my cluster setup, which is unfamiliar territory for me. The code seems to be hitting the catch block in the user.save() function of the register endpoint in app.js. I'm unsure if this indicates a problem with the code itself or with the MongoDB setup. Below are relevant snippets of code:

.env file (password obscured):

DB_URL=mongodb+srv://emc_admin-prime:[PASSWORD]@cluster1.9ifxogd.mongodb.net/?retryWrites=true&w=majority

dbConnect file:

const mongoose = require("mongoose");
require('dotenv').config()

async function dbConnect() {
  mongoose
    .connect(
        process.env.DB_URL,
      {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      }
    )
    .then(() => {
      console.log("Successfully connected to MongoDB Atlas!");
    })
    .catch((error) => {
      console.log("Unable to connect to MongoDB Atlas!");
      console.error(error);
    });
}

module.exports = dbConnect;

userModel file:

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: [true, "Please provide an Email!"],
    unique: [true, "Email Exist"],
  },

  password: {
    type: String,
    required: [true, "Please provide a password!"],
    unique: false,
  },
});

module.exports = mongoose.model.Users || mongoose.model("Users", UserSchema);

app.js file:

const express = require("express");
const app = express();
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');
const dbConnect = require('./db/dbConnect');
const User = require('./db/userModel');

dbConnect();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (request, response, next) => {
  response.json({ message: 'Server response' });
  next();
});

app.post('/register', (request, response) => {
  bcrypt.hash(request.body.password, 10)
    .then((hashedPassword) => {
      const user = new User({
        email: request.body.email,
        password: hashedPassword,
      });

      user
        .save()
        .then((result) => {
          response.status(201).send({
            message: 'User created successfully',
            result,
          });
        })
        .catch((error) => {
          response.status(500).send({
            message: 'Error creating user',
            error,
          });
        });
    })
    .catch((error) => {
      response.status(500).send({
        message: 'Password was not hashed successfully',
        error,
      });
    });
});

module.exports = app;

Answer №1

After overcoming this issue, I wanted to share how I found the solution.

The problem was actually linked to my setup in mongodb atlas, a seemingly insignificant setting that I wasn't aware of initially. It turned out that my main database user didn't have a specific role assigned, and this user access is crucial for my application to connect to the cluster. Once I changed it to "Atlas admin", I could successfully create a new user in the database.

UPDATE: There were some struggles with terminology mentioned earlier in the original message. The key difference was that I needed to insert a new record into the user collection. The reason for my inability to do so was because my database user (emc_admin-prime) lacked the appropriate role. To clarify, one refers to the DB user in mongodb atlas (emc_admin-prime), while the other pertains to a new entry in the user collection.

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

When a selection is made, the tab changes to a new URL. However, what happens if the tab is closed during the next selection change?

Is there a way for me to detect if the user has closed the browser tab that I opened and redirected to a URL? Here is the code I have so far. It checks if the user changes the value of a select dropdown, then it verifies whether the browser window was alr ...

What is the process for comparing values from two different collections using pymongo?

I have a situation where I have two distinct collections. For instance, one collection (collection1) includes details like ID, Name, and Identifier for various hostnames, while the other collection (collection2) contains information such as flowSourceType, ...

Tips for resolving the npm glob-parent dilemma

Vulnerability in glob-parent <5.1.2 Detected Severity Level: moderate Description: Regular expression denial of service - More information at https://npmjs.com/advisories/1751 Resolution: fix available through `npm audit fix` Affected Package: node_modu ...

Issue with Charts.js: The defined moment is missing when using chart.bundle.min.js

I successfully created a chart with charts.js and configured it, but now I aim to make the X Axis represent time. However, when attempting to implement this using the code below, I encounter the following console error: Uncaught ReferenceError: moment is n ...

Clicking on AngularJS ng-click to navigate to a different page within an Ionic framework application

My goal is to navigate to another page when clicking on a button in the Ionic navbar at the top. However, I am encountering an issue where upon clicking, all nav bar buttons disappear. Interestingly, using dummy codes triggers an alert successfully. But w ...

Unending loop caused by nested subscriptions - Angular / RxJS

I am currently implementing a nested subscribe operation, although I am aware that it may not be the most efficient method. Here is an example of what I have: this.route.params.subscribe((params) => { this.order$ .getMa ...

Choose a random element from an array and then modify the array

Can someone please assist me with this task? I am creating an array that corresponds to specific question numbers. var arrayCharge = []; for (var i = 2; i <= 45; i++) { arrayCharge.push(i); } I then utilize these numbers to display the respective quest ...

What is the best way to implement server side DB polling in ASP.Net?

Currently, I have an application built on angular.js, WebAPI, and mongodb. My main objective is to replace the client side polling with signalr. However, since mongodb does not trigger events on changes, I still need to periodically poll on the server side ...

Retrieve the JSON file only upon the first input change

On my backend, I have a JSON file containing suggested words for autocomplete in the search field. To improve performance, I don't want the JSON to load every time the page loads; instead, I only want it to load when someone wants to use the search f ...

Is there a way to create a custom user provider specifically for HWIOAuthBundle?

I am working on incorporating a social network login feature into my application. I need to handle the scenario where a user is not logged in yet by storing their information in the database, and if they already exist, logging them in. What should be inclu ...

Prisma - Organizing data by relation (for example, "Top Hashtags Used")

My goal is to display the "Most Used Hashtags" in my app. Essentially, it's a simple many-to-many relationship: model Post { id Int @id @default(autoincrement()) title String @db.VarChar(255) description String ...

Error encountered: index.html:17 - An InvalidStateError was thrown when attempting to execute the 'send' function on the XMLHttpRequest object. The object's state must be OPENED in order to send the Ajax request

When attempting to run index.html on a local host with xampp, an error is encountered: index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax @ index.html: ...

Automate the process of modifying specific data in tables through Javascript

I've been attempting to replicate the appearance of a stock-exchange board, but I'm encountering difficulties in updating text automatically without interrupting another. My attempts so far: var textPositive = ["2.0%", "1.7%" ...

Create a JavaScript function that checks for the existence of a file and returns a

I need to implement a JavaScript function that can determine if a file exists on a web server by using the fetch() method. Below is my current code snippet: let result = checkFile("index.html"); console.log("typeof(result) = " + typeof(result)); async fu ...

What is the best way to invoke a JavaScript function after an event or from a user interface?

I am struggling to call a JavaScript subroutine on the client-side after the server has completed its task. Even though I have tried putting breakpoints in <% ... %> areas between <script...> and </script>, it seems that VS2010 does not a ...

Maintain user authentication status in Vuex after page refresh

Hello, I have implemented a setup using Vuex and Laravel sanctum for user authentication. Below is the code snippet from my Vuex file auth.js: import axios from 'axios' export default { namespaced: true, state:{ authenticated: ...

There seems to be an issue with the integration of Bootstrap in my JavaScript file

Is there a way to ensure that each new data entry in the array appears next to each other rather than stacking beneath one another? This is a JavaScript file with HTML written in Bootstrap format. const collegeData = [{ name: "University of Penn ...

Designing a NoSQL database for a web application with email functionality

I'm currently in the process of developing a unique web messaging application that takes inspiration from popular email services like Gmail. The client side is being built with AngularJS, while MongoDB (with Mongoose) and NodeJS are being used for the ...

Incorporating an HTTP-based IFRAME into an HTTPS web address

My situation involves a PHP application running in HTTPS mode, within which there is an iframe containing an HTTP file. Both the parent and the iframe exist within the same domain. Strangely, I am unable to access the iframe source using HTTP. Is there a ...

Choose a specific example using the class name in nicEdit

Is there a way to select an instance using nicEdit based on its class name rather than just its id? For example: <div class="myInstance1"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed magna dolor, faucibus ac, iaculis non, cursus et ...