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;