Home > database >  Mongo DB already findOne method giving wired result
Mongo DB already findOne method giving wired result

Time:11-28

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

CodePudding user response:

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

CodePudding user response:

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 

CodePudding user response:

Can you try changing the code like this? with the Else method

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.

  • Related