0

How can I supply a username and password and check if the user already exists, and if it doesn't, I want to create the user. So it should basically be a get or create function.

I thought it could be something like

const username = 'username';
const password = 'password';

User.findOne({ username }).then(existingUser => {
  if (!existingUser) {
    return User.create({ username, password }).then(newUser => {
      return newUser;
    }).catch(console.error);
  }

  existingUser.comparePassword(password, (err, isMatch) => {
    if (!isMatch) { return null; }

    return existingUser;
  });
}).catch(console.error);

The problem is that I fully understand how to structure the promises.

I guess I should only have 1 catch instead of 2 as in this example.

So how could I structure this such that I always return either the user (whether it's an existing or new) or null?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Jamgreen
  • 10,329
  • 29
  • 113
  • 224

1 Answers1

0

I guess I should only have 1 catch instead of 2 as in this example.

Yes, you should.

So how could I structure this such that I always return either the user (whether it's an existing or new) or null?

You can use the following solution:

const username = 'username';
const password = 'password';

User
  .findOne({ username })
  .then(existingUser => {
    if (!existingUser) {
      return User.create({ username, password });
    }
    return new Promise((resolve, reject) => existingUser.comparePassword(password, (err, isMatch) => {
      if (!isMatch) {
        return reject(new Error('Incorrect password'));
      }
      resolve(user);
    });
  })
  .catch(console.error);
alexmac
  • 19,087
  • 7
  • 58
  • 69
  • Thanks! What if `existingUser.comparePassword` is also a promise instead of using a callback function? Could I somehow get rid of the `new Promise((res, rej) => ...)`? – Jamgreen Sep 11 '17 at 08:54
  • if `existingUser.comparePassword` returns a promise, you shouldn't use promise constructor here, because it's [explicit promise construction antipattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it). – alexmac Sep 11 '17 at 09:09