Skip to content

Instantly share code, notes, and snippets.

@gregorskii
Created March 25, 2017 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregorskii/e2ea2b49aea849fed656bee274228a36 to your computer and use it in GitHub Desktop.
Save gregorskii/e2ea2b49aea849fed656bee274228a36 to your computer and use it in GitHub Desktop.
Mongoose promise based object creation and validation
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