500 (Internal Server Error) on .save()

export const POST = async (request: any) => {
  const { email, password } = await request.json();

  await connect();

  const existingUser = await User.findOne({ email });

  if (existingUser) {
    return new NextResponse("Email is already in use", { status: 400 });
  }

  const hashedPassword = await bcrypt.hash(password, 5);
  const newUser = new User({
    email: email,
    password: hashedPassword,
  });
  try {
    await newUser.save();
    return new NextResponse("user is registered", { status: 200 });
  } catch (err: any) {
    return new NextResponse(err, {
      status: 500,
    });
  }
};

IT WAS WORKING FINE 2 DAYS AGO

Someone please help it gives POST 500 (internal server error) on line 38 of register.tsx which is

   try {
    
      const res = await fetch("/api/register", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email,
          password,
        })
      
      });
     
      if (res.status === 400) {
        setError("This email is already registered");
      }
      if (res.status === 200) {
        setError("");
        router.push("/login");
      }
      // if(res.status === 500){
      //   console.log("Error New Error");
      // }
    
    } catch(error) {
      // console.log("Error");
      setError("Error, try again");
      console.log(error);
    }

Hello @Ahnuf_Ather … You probably already guess that your use of await() and NextResponse() has issues. It’s not a MongoDB problem, it’s a Javascript and Next.js problem.

1 Like