Created
March 25, 2017 21:28
-
-
Save gregorskii/e2ea2b49aea849fed656bee274228a36 to your computer and use it in GitHub Desktop.
Mongoose promise based object creation and validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const email = req.body.email; | |
const password = req.body.password; | |
const query = UserModel.findOne({ email }); | |
query.exec() | |
.then((existingUser) => { | |
if (existingUser) { | |
logger.info('user found'); | |
return res.status(422).send({ error: 'Email in use' }); | |
} | |
const user = new UserModel({ | |
email, | |
password | |
}); | |
return user.save() | |
.then(() => { | |
res.send({ error: false }); | |
}) | |
; | |
}) | |
.catch((err) => { | |
logger.error(err); | |
if (err.name === 'ValidationError') { | |
return res.status(422).send( | |
{ error: `You must provide: ${Object.keys(err.errors).join(', ')}` } | |
); | |
} | |
return res.send({ error: true }); | |
}) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment