I'm running a transaction in express js. Following is the code:
app.post('/register', (req, res) => {
const { name, email, password } = req.body;
const hash = bcrypt.hashSync(password);
db.transaction(trx => {
trx.insert({
hash: hash,
email: email
})
.into('login')
.then(() => { return trx('login').select('email').where('email', email).then(loginEmail => loginEmail[0].email) })
.then(loginEmail => {
trx('users') **//if I add return before this line**
.insert({
email: loginEmail,
name: name,
joined: new Date()
})
})
.then(() => { return trx('users').select('*').where('email', email).then(data => res.json(data[0])) })
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(404).json(err));
});
When I register a user using postman through this code, only the login table is getting the entries but the users table is not getting any entries, therefore resulting in an incomplete transaction. I'm also not getting any response and the status is "200 ok". According to the code I should be getting a response in json format of the registered user. When I add return statement to the line which I've marked using comment "// if I add return before this line" everything runs fine and I get a proper response. I cannot understand why and how is this happening. I'm running this on node server and my database is in mysql. I'm already telling in advance that .returning() is not supported in mysql or mysql2 Please someone explain what is happening here. Thanks in advance.
I expected a json response of the registered user. But I'm getting no response and there is also not any error in the postman window.