ii a
ii a

Reputation: 15

Find if username and email exist in MongoDB

I'm trying to rewrite my code to check if username and email already exist in my MongoDB before creating a new user. Right now, my code checks to see if an email exists before creating a new user. It works but I'm having trouble finding a way to add code to see if the username exists aswell

I've tried the code below but it will only return an error for email but won't return the error for username.

User.find({
    $or: [{ email: req.body.email }, { username: req.body.username }]
  }).then(user => {
    if (user) {
      if (User.findOne({ email: req.body.email })) {
        errors.email = "Email already exists";
        return res.status(400).json(errors);
      }
      if (User.findOne({ username: req.body.username })) {
        errors.username = "Username already exists";
        return res.status(400).json(errors);
      }
    } else {
      const newUser = new User({
        username: req.body.username,
        email: req.body.email,
        password: req.body.password
      });

      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });

My code that works for only checking if email exists:

User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      errors.email = "Email already exists";
      return res.status(400).json(errors);
    } else {
      const newUser = new User({
        username: req.body.username,
        email: req.body.email,
        password: req.body.password
      });

      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });

I need the code to check if the username exists and return and error. Then check if the email exists and return an error. Then create the new user if neither exist

Upvotes: 1

Views: 6105

Answers (2)

Ernesto
Ernesto

Reputation: 4272

export const myCoolEndPoint = async (req, res) => {
    try {
        const {username="", email=""} = req.body;

        const exists = await User.find({email: email});

        if (exists === null) {
            return res.status(404).send({message: "User Not found"});
        }

        if (exists.username !== username) {
            return res.status(404).send({message: "NOt found"});
        }

        return bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(exists.password, salt, (err, hash) => {
                if (err) throw err;
                exists.password = hash;
                const saved = await newUser.save();
                // 202 means created
                return res.status(202).send({message: "User created"})
            });
        });
    } catch (error) {
        res.status(500).send({message: "you broke me </3"});
    }
}

Upvotes: 0

Mohammed Amir Ansari
Mohammed Amir Ansari

Reputation: 2401

The query you made is correct, All you need to do is just check what condition is returning you the user. The code for the same is:

User.findOne({
        $or: [{
            email: req.body.email
        }, {
            username: req.body.username
        }]
    }).then(user => {
        if (user) {
            let errors = {};
            if (user.username === req.body.username) {
                errors.username = "User Name already exists";
            } else {
                errors.email = "Email already exists";
            }
            return res.status(400).json(errors);
        } else {
            const newUser = new User({
                username: req.body.username,
                email: req.body.email,
                password: req.body.password
            });

            bcrypt.genSalt(10, (err, salt) => {
                bcrypt.hash(newUser.password, salt, (err, hash) => {
                    if (err) throw err;
                    newUser.password = hash;
                    newUser
                        .save()
                        .then(user => res.json(user))
                        .catch(err => console.log(err));
                });
            });
        }
    })
    .catch(err => {
        return res.status(500).json({
            error: err
        });
    });

Hope this helps :)

Upvotes: 2

Related Questions