skip to Main Content

I am trying to create a new user in mongodb and looking for existing user but even if a am sending request with new user details it is still showing that User alreadyExists

export const signUp = async (req, res) => {
  const {email, password, username, roomid} = req.body;
  try {
    console.log(req.body);
    let existingUser = User.findOne({email});
    console.log(existingUser);
    if (existingUser) res.status(400).json({message: 'User already exists!!'});

    const hashedPassword = await bcrypt.hash(password, 12);

    const result = await User.create({
      email,
      password: hashedPassword,
      username,
      roomid,
    });

    const token = jwt.sign(
      {email: existingUser.email, id: existingUser._id},
      'test',
      {expiresIn: '1hr'}
    );
    res.status(201).json({result, token});
  } catch (err) {
    console.log(err);
  }
};

Help Please

Someone just solve the problem of new user creation

3

Answers


  1. Try this

    const existingUser = db.collection('users').findOne({ email: email }); 
    
    if (existingUser) { 
      res.json({ 
        message: 'User already exists', 
        existingUser: existingUser 
      }); 
      client.close(); 
      return; <-- stop executing code if user already exists 
    } //checks if user already exists 
    
    Login or Signup to reply.
  2. Change line, because even after this line the program continues to run.

    if (existingUser) res.status(400).json({message: 'User already exists!!'});
    

    To:

    if (existingUser) return res.status(400).json({message: 'User already exists!!'});
    

    You need to return key.

    Login or Signup to reply.
  3. Try changing the code with the Else method so:

    export const signUp = async (req, res) => {
      const {email, password, username, roomid} = req.body;
      try {
        
        console.log(req.body);
        
        let existingUser = User.findOne({email});
        
        console.log(existingUser);
        
        if (existingUser){
            return res.status(400).json({message: 'User already exists!!'});
    
        }else{
          const hashedPassword = await bcrypt.hash(password, 12);
    
          const result = await User.create({
            email,
            password: hashedPassword,
            username,
            roomid,
          });
      
          const token = jwt.sign(
            {email: existingUser.email, id: existingUser._id},
            'test',
            {expiresIn: '1hr'}
          );
          return res.status(201).json({result, token});
        }
    
    
      } catch (err) {
        console.log(err);
      }
    };
    

    Note: Don’t forget to turn the server off and then on again.

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