0

My mongoDB findOne which was working before because it was responsible for checking if an email exist in my database, but as soon i added the .sort to it, it throws an error UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'email' of null at User.findOne.sort.then.user But if i remove the sort, it will work again including the email do exist validation.

Here is the code

router.post('/register', (req, res) => {
  const { errors, isValid } = validateRegisterInput(req.body);

  // Check Validation 
  if (!isValid) {
    return res.status(400).json(errors);
  }

  User.findOne({ email : req.body.email }).sort({unitNo : -1}).then(user => {
    if (user.email === req.body.email) {
    errors.email = 'Email already exists';
     return res.status(400).json(errors);
    } else {
      // create my secret token for email verification
        const secretToken = randomstring.generate();
        const defaultNo = user[0].unitNo;
        const unitNo = String(Number(defaultNo)+1).padStart(4, '0');
        const newUser = new User(
      {
        email: req.body.email,
        password: req.body.password,
        phone : req.body.phone,
        fullname: req.body.fullname,
        secretToken,
        unitNo,
        });
      const DOMAIN = "******.mailgun.org";
      const mg = mailgun({apiKey: "*******", domain: DOMAIN});
      const data = {
                    from: 'no-reply@yourwebapplication.com', 
                    to: newUser.email,
                    subject: 'Account Verification Token', 
                    text: 'Hello,\n\n' + 'Please verify your account by clicking the link: \nhttp:\/\/' + req.headers.host + '/\api/users/verify\/' + newUser.secretToken + '.\n' 
                   };
      mg.messages().send(data, function (error, body) {
    console.log(body);
});
     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));
        });
      });
    }
  });
});

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
phemieny7
  • 803
  • 7
  • 21
  • findOne returns one document if any, not a cursor. You can't sort it. – rodrigoap Sep 20 '19 at 21:18
  • okay thank you, will see what i can do about it – phemieny7 Sep 20 '19 at 21:48
  • `findOne` returns a single document... what is there to sort??? – Matt Oestreich Sep 20 '19 at 23:02
  • @MattOestreich The point would be where the criteria does match more than one document and you wanted to only return the "first or last" result when sorted by a particular field ( or combination of fields ). Nonetheless, "checking if an email exists" really*should* only ever expect **one** result only. But there is a use case where it does actually apply. Just probably not here. – Neil Lunn Sep 21 '19 at 04:33
  • Note the syntax is slightly different between `mongoose` and the node driver for `mongodb` for how to implement a `sort` in a `findOne()` operation. Though the question lacks the `mongoose` tag, that's *probably* what is being used here. Hence the two duplicate sources of answers. Use the one appropriate to the actual driver in use. – Neil Lunn Sep 21 '19 at 04:36

0 Answers0