Tuesday 6 June 2017

How to Async Mongoose Controller

Trying to configure a SignUp() controller that can update multiple (separate) user accounts when a referral code is provided by the user.

Basic Flow:

  1. Verify email doesn't already exist in system
  2. Find the driver w/ userID matching the rider's refCode (FindOneAndUpdate)
  3. If Found: Add the userID of each user to the other users [clients] list
  4. Only need to do a refCode match if isRider
  5. If any of those fail... Return the specific error to the client/user


This does not work. But essentially, this is what I'm trying to accomplish...

// POST `/signup` (Create a new local user)
export function signUp(req, res, next) {
  const newUser = new User({
    email: req.body.email,
    password: req.body.password,
    profile: {
      userID: req.body.userID,
      refCode: req.body.refCode,
      isRider: req.body.isRider
    }
  });

  User.findOne({ email: req.body.email }, (findErr, foundUser) => {
    if (foundUser) {
      return res.status(409).send('This e-mail address already exists');
    }
    // riders must link to a driver
    if (req.body.isRider) {
      // find driver + add rider ID to clients
      return User.findOneAndUpdate({ 'profile.userID': req.body.refCode }, { $push: { clients: newUser.profile.userID }}).exec()
        .then((err, foundDriver) => {
          if (err) {
            return res.status(409).send('Error searching for driver');
          } else if (!foundDriver) {
            return res.status(409).send(`We can't find your driver (${req.body.refCode})!`);
          }
          // add driver ID to rider's clients
          newUser.clients = [req.body.refCode];

          return newUser.save((saveErr) => {
            if (saveErr) return next(saveErr);
            return req.logIn(newUser, (loginErr) => {
              if (loginErr) return res.sendStatus(401);
              return res.json(newUser.profile);
            });
          });
        });
    }

    return newUser.save((saveErr) => {
      if (saveErr) return next(saveErr);
      return req.logIn(newUser, (loginErr) => {
        if (loginErr) return res.sendStatus(401);
        return res.json(newUser.profile);
      });
    });
  });
}

I'm pretty sure that I'm just not setting up the promise correctly. I've to get a straight promise solution, but no luck. Most of the examples out there all seem different. I also couldn't figure out how to handle/throw specific errors using the mongoose docs.

Greatly appreciated if anyone can lend a hand, Thx!



via JRodl3r

No comments:

Post a Comment