All I want to do is run a query, check if an email address is already registered and if so reject the request, if not run some validation and then create the user in my users table. This is a bit of a shell, the code was originally based off https://github.com/vitaly-t/pg-promise-demo, that code is amazing, but I am not. Promises are completely nonsensical to me, I have no clue what I should be returning or where.
This code runs and achieves what it's supposed to, but then it hits the catch and send back "Cannot read property 'then' of undefined". When I try chaining the second .then so that it's not within the first .then() I get errors that I'm trying to alter res after it's already been sent.
Can someone please help me understand what's wrong here and how to fix it?
useradd: function (req, res) {
db.users.findbyemail(req.body.email)
.then(function(data){
if( typeof data === undefined || data === null) {
db.users.add({
provider: 'local',
email: req.body.email,
password: req.body.password,
salt: 'salt',
displayName: req.body.displayName })
.then(function(data){
res.json({
success: true,
data: "Account created"
})
})
} else {
res.json({
success: false,
error: "Email address " + req.body.email + " is already registered on this site"
})
}
})
.catch(function(error){
res.json({
success: false,
error: error.message || error
})
})
}