I am new to Knex and I tried some transactions. When I send the email address to the users table it sends it like {"email":"[email protected]"}
and I am lost, can anybody help me?
app.post('/register', (req, res) =>{
const {email, name, password } = req.body;
const hash = bcrypt.hashSync(password);
db.transaction(trx =>{
trx.insert ({
has: hash,
email: email
})
.into('login')
.returning('email')
.then (loginEmail => {
return trx('users')
.returning('*')
.insert({
email:loginEmail[0],
name: name,
joined: new Date()
}).then(user =>{
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)`
})
})
What has happened is that you are inserting loginEmail[0]
in the second insert.
What you should be inserting is loginEmail[0].email
, if not, you are technically inserting an object looking like { email: '[email protected]' }
app.post('/register', (req, res) => {
const { email, name, password } = req.body;
const hash = bcrypt.hashSync(password);
db.transaction(trx => {
trx.insert ({
hash, // make sure you fix this spelling. also, in modern JS it's enough writing like this (no need for email: email)
email
})
.into('login')
.returning('email')
.then (dbResponse => {
return trx('users')
.returning('*')
.insert({
email: dbResponse[0].email,
name,
joined: new Date(),
}).then(user => {
res.json(user[0]);
})
})
.then(trx.commit)
.catch(trx.rollback)`
})
})
Took the liberty at adding some formatting and replacing the variable for the dbResponse so it is slightly clearer.