skip to Main Content

I am creating a user authentication site with mern and I am having problem posting to mongoDB. I have tried many options and the problem persists. It gives lots of error messages. I used nodejs, expressjs and mongodb for configuring the backend. Please help me out

[controller]:

const User = require('../model/User');
// const bcrypt = require('bcryptjs');

exports.createUser = async (req,res) => {

try{ 
    // req.body.password = await bcrypt.hash(req.body.password,8);
   const user = new User(req.body);
    
    await user.save();

    return res.status(201).json({success: true, user});
}
catch(e){
    return res.status(400).json({success: 
false,message:e.message});
 }
}
[route]:

const express = require('express');
const router = express.Router();

const { createUser,
    getAllUser,
    getSingleUser,
    updateUser,
    deleteUser,
    login} = require('../controller/user');


 // CREATE USER

 router.post('/user',createUser);
[module]:

const mongoose =  require('mongoose');
const validator = require('validator');
// const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
name:{
    type: String,
    minlength: 3,
    unique:true,
    maxlength: 20,
    required:true ,
    trim: true

    },
    age:{
    type:Number,
    validate(value){
        if(value < 18){
            throw new Error(`Age can't be less than 18`)
        }
    }
   },
   email:{
    type:String,
    required:true,
    unique: true,
    lowercase:true,
    trim:true,
    validate(value){
        if(!validator.isEmail(value)){
            throw new Error('Email is not valid');
        }
     }
    },
    password:{
    type:String,
    required:true
    },
    });

   userSchema.pre('save', async function(next){

const user = this;

console.log(user.isModified('password'));

if(user.isModified('password')){
    user.password = await (user.password,8);
}
next();
});

const User  = mongoose.model('User',userSchema);

module.exports = User;
[form]:

import React, { useEffect, useState } from "react";
import * as Components from "./FormComponents";
import axios from "axios";
const Signin = (props) => {
const [signIn, toggle] = React.useState(true);
const [createUser,setcreateUser] = useState({
  name:'',
  email:'',
  password:'',
  age:30,
});
useEffect(()=>{
  axios.get('http://localhost:4040/user').then(res => 
console.log(res.data))
},[])
const handleInput = (event) => {
  const {name,value} = event.target;
  setcreateUser({...createUser, [name]:value});
  // console.log(createUser);
 }
 async function handlesubmit(event){
  event.preventDefault();
  console.log(createUser);
  try{
    const rep = await axios.post('http://localhost:4040/user',
    {createUser}, {
      headers: {
      'Content-Type': "application/json",
  }})
    .then(Response => console.log(Response))
    .catch(err => console.log(err));
    console.log(rep.data);
  }catch(err){
    console.log(err.Response)
  }
}

return(
    <Components.Container>
      <Components.SignUpContainer signingIn={signIn}>
        <Components.Form  onSubmit={handlesubmit}>
          <Components.Title>Create Account</Components.Title>
          <Components.Input type="text" name="name" value={createUser.name} placeholder="Name" onChange={handleInput}/>
          <Components.Input type="email" name="email" value={createUser.email} placeholder="Email" onChange={handleInput}/>
          <Components.Input type="password" name="password" value={createUser.passord} placeholder="Password" onChange={handleInput}/>
          <Components.Input type="number" name="age" value={createUser.age} placeholder="Confirm Password" />
          <Components.Button >Sign Up</Components.Button>
        </Components.Form>
      </Components.SignUpContainer>
[dbconnection]:

const express = require('express');
const mongoose =  require('mongoose');
// const colors = require('colors')
const app = express();
const cors = require('cors')

app.use(cors({
origin: 'http://localhost:3000', // <-- location of the react server
}))

// middleware
app.use(express.json());

var url = 'mongodb://127.0.0.1:27017/restmongose';

mongoose.connect(url)
.then(() => console.log("Database Connected Successfully!"))
.catch((err) => console.error(err));

// Schema(Shape of a document)

const userRoutes = require('./routes/user')
const taskRoutes = require('./routes/task')

app.use(userRoutes);
app.use(taskRoutes);

const port = process.env.PORT||4040;

app.listen(port, () => console.log(`Server running at port ${port}`));

2

Answers


  1. I’d be happy to help you troubleshoot the issue you’re facing with posting to MongoDB in your MERN (MongoDB, Express, React, Node.js) authentication site. To provide you with accurate guidance, I’ll need some more information about the specific errors you’re encountering and the code you’ve written. However, I can give you a general troubleshooting process and some common solutions that might help you resolve the problem.

    Here’s a step-by-step approach to troubleshooting the issue:

    1. Check MongoDB Connection:
      Ensure that your Node.js server is successfully connected to your MongoDB database. Check the database URL, credentials, and make sure your MongoDB instance is up and running.

    2. Error Messages:
      Share the specific error messages you’re encountering. This will give me a better understanding of the issues you’re facing and help me provide more targeted solutions.

    3. Code Review:
      Share the relevant parts of your code related to posting data to MongoDB. Specifically, provide the code for your Express route that handles the POST request and interacts with MongoDB.

    4. Validate Data:
      Make sure the data you’re trying to insert into the database is valid and properly formatted. Check if any required fields are missing or if you’re trying to insert incorrect data types.

    5. Express Middleware:
      Verify that you’re using appropriate middleware to handle incoming data. For example, you might use express.json() middleware to parse JSON data from requests.

    6. Try Different Routes/Endpoints:
      Sometimes, errors can be specific to certain endpoints or routes. Try creating a simplified route with minimal code to see if you can successfully insert data into the database. This can help narrow down the source of the issue.

    7. Error Handling:
      Implement proper error handling in your Node.js code. Use try and catch blocks to capture and log errors. This will help you identify the specific point where the error is occurring.

    8. Logging:
      Add console logs at different stages of your code to trace the flow and identify where the error might be happening.

    9. Database Access:
      Make sure you’re using the correct methods to interact with MongoDB using a library like mongoose or the native MongoDB driver for Node.js.

    10. Database Schema:
      Check your MongoDB schema definition to ensure it matches the structure of the data you’re trying to insert.

    11. Dependency Versions:
      Ensure that your Node.js, Express, MongoDB, and other relevant libraries are up to date and compatible with each other.

    12. Network Requests:
      If you’re making requests from the frontend (React) to the backend (Node.js), ensure that your API requests are being correctly sent and received. Use tools like Postman or browser developer tools to debug your API requests.

    By following this troubleshooting process and sharing more specific details, you’ll be in a better position to identify and resolve the issues you’re facing with posting to MongoDB in your MERN authentication site. If you can provide more information or specific error messages, I’d be able to give you more targeted assistance.

    Login or Signup to reply.
  2. I assume you send the correct valid age.
    In the model, You defined the age should be more than 18.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search