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
?