skip to Main Content

I am trying to create user login and sign up in NodeJS with mongoDB, but in login module i am getting this error –

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

SyntaxError: await is only valid in async functions and the top level
bodies of modules.

Here is my code of "user-controller.js" file code.

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

// next is used to move to the next middleware task
const signup = async (req, res, next) => {
  const { name, email, password } = req.body;

  let existingUser;
  try {
    existingUser = await User.findOne({ email: email });
  } catch (err) {
    console.log(err);
  }
  if (existingUser) {
    return res.status(400).jason({ message: 'User already exists! Login Instead' })
  }

  const hashedPassword = bcrypt.hashSync(password);

  const user = new User({
    name,
    email,
    password: hashedPassword,
  });

  try {
    await user.save();
  } catch (err) {
    console.log(err);
  }

  return res.status(201).json({ message: user })
};

const login = (req, res, next) => {
  const { email, password } = req.body;

  let existingUser;
  try {
    existingUser = await User.findOne({ email: email });

  } catch (err) {
    return new Error(err);
  }
  if (!existingUser) {
    return res.status(400).json({ message: "User not found. Signup Please" })
  }
  const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password);
  if (!isPasswordCorrect) {
    return res.status(400).json({ message: "Invalid Email / Password" })
  }
  return res.status(200).json({ message: "Successfully logged in" })
}

exports.signup = signup;
exports.login = login; 

How to resolve it?

2

Answers


  1. We can only use await inside an async function, in your case

    const login = async (req, res, next) => {
      // We can use await here
    }
    
    Login or Signup to reply.
  2. Instead of try catch we can do something like this

    try {
        User.findOne({ email: email }).then((response)=>{
            //do something
        });
    } catch (err) {
         //do something
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search