mongodb Mongo DB已经找到一个方法,给出连接结果

bq8i3lrv  于 2022-11-28  发布在  Go
关注(0)|答案(3)|浏览(150)

我尝试在mongodb中创建一个新用户并查找existing user,但即使我发送了包含新用户详细信息的请求,它仍然显示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);
  }
};

救命
有人刚刚解决了新用户创建的问题

6mzjoqzu

6mzjoqzu1#

更改行,因为即使在该行之后程序仍继续运行

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

结束日期

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

您需要return密钥

sxissh06

sxissh062#

你能试着用Else方法这样修改代码吗?

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);
  }
};

注意:不要忘记关闭服务器,然后再打开。

k97glaaz

k97glaaz3#

试试这个

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

相关问题