Home > Back-end >  Node Js (express JS) is not inserting the record into MongoDB, generating error
Node Js (express JS) is not inserting the record into MongoDB, generating error

Time:01-03

When I am trying to insert the user's record into the MongoDB database it shows an error (500 Internal Server Error) on the postman with "message": "Password was not hashed successfully".

For the backend, I am using Express JS. And my Connection String with MongoDB is :

DB_URL=mongodb srv://NSreactauth:[email protected]/reactauthapp?retryWrites=true&w=majority

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");

// require database connection
const dbConnect = require("./db/dbConnect");
const User = require("./db/userModel");
const auth = require("./auth");

// execute database connection
dbConnect();

// Curb Cores Error by adding a header here
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content, Accept, Content-Type, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS"
);
next();
});

// body parser configuration
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();
});

// register endpoint
app.post("/register", (request, response) => {
// hash the password
bcrypt.hash(request.body.password, 10)
.then((hashedPassword) => {
  // create a new user instance and collect the data
  const user = new User({
    email: request.body.email,
    password: hashedPassword,
  });

  // save the new user  // return success if the new user is added to the database successfully
  user.save().then((result) => {
      response.status(201).send({
        message: "User Created Successfully",
        result,
      });
    })
    // catch erroe if the new user wasn't added successfully to the database
    .catch((error) => {
      response.status(500).send({
        message: "Error creating user",
        error,
      });
    });
})
// catch error if the password hash isn't successful
.catch((e) => {
  response.status(500).send({
    message: "Password was not hashed successfully",
    e,
   });
   });
  });


 module.exports = app;

CodePudding user response:

async function hashPassword(password) {
  const salt = await bcrypt.genSalt(10)
  const hashedPassword = await bcrypt.hash(String(password), salt)
  return hashedPassword
}


app.post("/register", async(request, response) => {
// hash the password
const hashedPassword = await hashPassword(req.body.password);
const user = new User({
    email: request.body.email,
    password: hashedPassword,
  });

  // save the new user  // return success if the new user is added to the database successfully
  user.save().then((result) => {
      response.status(201).send({
        message: "User Created Successfully",
        result,
      });
    })
    // catch erroe if the new user wasn't added successfully to the database
    .catch((error) => {
      response.status(500).send({
        message: "Error creating user",
        error,
      });
    });
  });

CodePudding user response:

I would suggest making your code as simple as you can.

app.post("/register", async (request, response) => {
    try {
        let hashedPassword = await bcrypt.hash(request.body.password, 10) // create has password

        const user = new User({
            email: request.body.email,
            password: hashedPassword,
        }); //prepare user data
        await user.save() //save user data
        response.status(201).send({
            message: "User Created Successfully",
            user,
        }); //send success response
    } catch (e) {
        response.status(500).send({
            message: e.message,
            error,
        }); //send error response
    }
})
  • Related