skip to Main Content

im trying to set up a Mock social media site, im running some code to prevent the request from making users with the same username. So i have a loop going through all the users, comparing the usernames to the request username, checking if theyre the same.
whenever the loop detect that they are the same it’s supposed to throw an error and send it to the 2nd try catch block

  try {
    const usersArr = await mongodb.getDb().db().collection("users").find();
    const users = usersArr.toArray().then((lists) => {
      for (let i = 0; i < lists.length; i++) {
        if (lists[i].userName == req.body.userName) {
          console.log(i);
          throw new Error("username is already in use");
        }
      }
    });
    try {
      const user = {
        userName: req.body.userName,
        password: req.body.password,
        posts: [],
      };

      const response = await mongodb
        .getDb()
        .db()
        .collection("users")
        .insertOne(user);
      if (response.acknowledged) {
        res.status(201).json(response);
      }
    } catch (error) {
      res.status(500).json(error);
    }
  } catch (error) {
    res.status(500).json(error);
    console.log(error);
  }
}; ```

instead it throws the error, prevents the insert, and then the app crashes 
could someone please help me with this

2

Answers


  1. I’m a beginner in JS, but try to put some alert() calls within your code, and see where it doesn’t work.

    Login or Signup to reply.
  2. Why don’t you want to check for existing username directly in the MongoDB query like below.

    try{
      const existingUser = await mongodb
      .getDb()
      .db()
      .collection("users")
      .findOne({ userName: req.body.userName });
    
      if (existingUser) {
        return res.status(400).json({ error: "Username is already in use" });
      }
      // rest of the code
    } catch (error) {
      res.status(500).json(error);
      console.log(error);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search