Error code 8000 when creating new user

I am extremely new to MongoDB and am just now pushing more and more into fullstack development (mostly front end historically). I’m trying to build a simple authentication end point, and everything seems perfectly fine and error free (connection to DB is successful), until I try to create a new user in postman and it seems like no matter what I do, I get the following error:

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

The issue I’m having is this error doesn’t seem to be telling me much and my attempts at searching on it (google, mongo docs) have not given me much to go on. I’m not necessarily looking to be handed the answer, but it would be nice if I could be pointed in the right direction because at this point I’m at a complete loss and have no idea where to even start looking. I’m fairly certain the issue isn’t in code but in my cluster setup, mostly because that’s the area of this that is by far most foreign to me, but I’m not really sure where to even start looking on that end of things. It seems to be hitting the catch in the user.save() block of the register endpoint in app.js, but I’m not sure if that implies an issue with the code, or an issue with the setup in mongo. Below are some potentially relevant code snippets:

.env file (password intentionally 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: 'Hey! This is your 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;

I was able to get this resolved, so posting my answer here.

This was in fact related to the setup within mongodb atlas, and, predictably, was a seemingly minor setting that I was just unaware of (and unaware of its importance). My primary database user did not have a built-in role selected, and it seems that user access is the conduit by which my application can access the cluster. Once I updated it to “Atlas admin”, I was able to successfully add a new user to the DB.

EDIT: Some terminology challenges here, as referenced up top in the original post. The distinction here is that I needed to add a new entry to the user collection, I was being blocked from accessing it though because my database user (emc_admin-prime) did not have the proper role selected. So, one is the DB user within mongodb atlas (emc_admin-prime), the other is a new entry to a collection called user.

From your original code fragment you’re just adding into a collection called “user” as opposed to actually adding a database user?
In which case you don’t want to grant an application user that much power, you should be able to grant it a lower role which has read and write access.

Yes, the goal was to simply add to a collection called user. This plays into the terminology challenges I reference up top; the intention here ultimately is to build an application that will allow new users to sign up and create an account, and I think the “user” in that context is getting conflated with the “database user” from the POV of the cluster itself. My answer should in fact be the correct one from how I understand things, and it definitely resolved the issue. The database user “emc_admin-prime”, as seen in the db_url, should be able to have full access to anything within that cluster, I was just unaware I needed to assign a role to specify that and it was the thing preventing me from adding a new entry to the user collection.

Thanks for the feedback! I’m definitely open to being schooled on if there’s a more nuanced way I should be setting up that DB user, keeping in mind that that is intended to be the primary admin and so should be able to access most if not all. The overall gist of the issue though was that I needed to add an entry to the user collection, and it seems the lack of a specified role on the emc_admin-prime DB user was the reason I was getting the 500 error.

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