skip to Main Content

here I am trying to insert an object to Mongodb via POST using axios.the object that I send gets successfully inserted in the MongoDB collections. after inserting the object I need to redirect to the home page but instead of this I am getting axios error request failed with status code 500 inside axios response data giving message No write concern mode named majority found in replica set configuration

here is my code

UserSignUp.jsx

export default function SignUpScreen() {
  const navigate = useNavigate();
  const { search } = useLocation();
  const redirectInUrl = new URLSearchParams(search).get('redirect');
  const redirect = redirectInUrl ? redirectInUrl : '/';

  const [name,setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('')

  const { state, dispatch: ctxDispatch } = useContext(Store);
  const { userInfo } = state;

  const submitHandler = async e => {
    e.preventDefault();
    if(password !== confirmPassword) {
        toast.error('Passwords do not match');
        return;
    }
    try {
      const { data } = await axios.post('/api/users/signup', {
        name,
        email,
        password,
      });
      ctxDispatch({ type: 'User_SignIn', payload: data });
      localStorage.setItem('userInfo', JSON.stringify(data));
      navigate(redirect || '/');
    } catch (err) {
      toast.error(getError(err));
      console.log(err);
    }
  };
  useEffect(() => {
    if (userInfo) {
      navigate(redirect);
    }
  }, [navigate, userInfo, redirect]);
  return (
    <Container className='small-container'>
      <Helmet>
        <title>Sign Up</title>
      </Helmet>
      <h1 className='my-3'>Sign Up</h1>
      <Form onSubmit={submitHandler}>
        <Form.Group className='mb-3' controlId='name'>
          <Form.Label>Name</Form.Label>
          <Form.Control
            required
            onChange={e => setName(e.target.value)}
          />
        </Form.Group>
        <Form.Group className='mb-3' controlId='email'>
          <Form.Label>Email</Form.Label>
          <Form.Control
            type='email'
            required
            onChange={e => setEmail(e.target.value)}
          />
        </Form.Group>
        <Form.Group className='mb-3' controlId='password'>
          <Form.Label>Password</Form.Label>
          <Form.Control
            type='password'
            required
            onChange={e => setPassword(e.target.value)}
          />
        </Form.Group>
        <Form.Group className='mb-3' controlId='confirmPassword'>
          <Form.Label>Confirm Password</Form.Label>
          <Form.Control
            type='password'
            required
            onChange={e => setConfirmPassword(e.target.value)}
          />
        </Form.Group>
        <div className='mb-3'>
          <Button type='submit'>Sign Up</Button>
        </div>
        <div className='mb-3'>
          Already have an account?{' '}
          <Link to={`/signin?redirect=${redirect}`}>Sign-In</Link>
        </div>
      </Form>
    </Container>
  );
}

userRouter.js

userRouter.post(
  '/signup',
  expressAsyncHandler(async (req, res) => {
    const newUser = new User({
      name: req.body.name,
      email: req.body.email,
      password: bcrypt.hashSync(req.body.password),
    });
    try {
            const user = await newUser.save();
            res.send({
              _id: user._id,
              name: user.name,
              email: user.email,
              isAdmin: user.isAdmin,
              token: genarateToken(user),
            });
    } catch (err) {
     res.status(500).send(err)
    }
  })
);
export default userRouter;

UserModel.js

const userSchema = new mongoose.Schema(
    {
        name: {type:String, required: true},
        email: {type:String, required: true, unique:true},
        password: {type:String, required: true},
        isAdmin: {type: Boolean, default: false,required: true},
    },
    {
        timestamps: true
    }
)
const User = mongoose.model("User", userSchema);
export default User;

Routes in App.js

<Routes>
              <Route path='/product/:slug' element={<ProductScreen />} />
              <Route path='/cart' element={<CartScreen />} />
              <Route path='/signin' element={<SignInScreen />} />
              <Route path='/signup' element={<SignUpScreen />} />
              <Route path='/shipping' element={<ShippingAddressScreen />} />
              <Route path='/' element={<HomeScreen />} />
            </Routes>

mongoURI in .env file

MongoURI = mongodb+srv://Ecom:[email protected]/EcomDB?retryWrites=true&w=majority

Error in Console

AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
code: "ERR_BAD_RESPONSE"
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
message: "Request failed with status code 500"
name: "AxiosError"
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response: {data: {…}, status: 500, statusText: 'Internal Server Error', headers: {…}, config: {…}, …}
[[Prototype]]: Error

error showing in postman

{
    "code": 79,
    "codeName": "UnknownReplWriteConcern",
    "errInfo": {
        "writeConcern": {
            "w": "majority,",
            "wtimeout": 0,
            "provenance": "clientSupplied"
        }
    },
    "result": {
        "n": 1,
        "electionId": "7fffffff0000000000000067",
        "opTime": {
            "ts": {
                "$timestamp": "7136856325794824195"
            },
            "t": 103
        },
        "writeConcernError": {
            "code": 79,
            "codeName": "UnknownReplWriteConcern",
            "errmsg": "No write concern mode named 'majority,' found in replica set configuration",
            "errInfo": {
                "writeConcern": {
                    "w": "majority,",
                    "wtimeout": 0,
                    "provenance": "clientSupplied"
                }
            }
        },
        "ok": 1,
        "$clusterTime": {
            "clusterTime": {
                "$timestamp": "7136856325794824195"
            },
            "signature": {
                "hash": "OlulLu5s5TwSvEO60v4+6td/yt8=",
                "keyId": {
                    "low": 7,
                    "high": 1648401224,
                    "unsigned": false
                }
            }
        },
        "operationTime": {
            "$timestamp": "7136856325794824195"
        }
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    i was getting "errmsg": "No write concern mode named 'majority,' found in replica set configuration", in postman. i wrote my mongodb connection url in .env file.

    1. at .env file if you write mongoURI code inside single quotes or semicolon at the end . the following error will occur.

    2. removing code after ? in mongoURI my errors disappear for example

      MongoURI = mongodb+srv://Ecom:[email protected]/EcomDB?

    from this

    MongoURI = mongodb+srv://Ecom:[email protected]/EcomDB?retryWrites=true&w=majority


  2. You userSchema has isAdmin required field, but not provided in the signup Action. Modify isAdmin optional or provide while you creating new User

    const newUser = new User({
          name: req.body.name,
          email: req.body.email,
          password: bcrypt.hashSync(req.body.password),
          // isAdmin: missing
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search