I wanted to made a query to the mysql database if the username already exists he should throw me a message and if not, show me the new id. I wanted to check if the query result.lenght is higher than 0. however it throws the error "Cannot read property 'length' of undefined"
Service file
const connect = () =>
mysql.createConnection({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE
});
const insert = (conn, user) => {
return conn.query(`insert into user(username, firstName, lastName, password)
values(?,?,?,?)`,
[
user.username,
user.firstName,
user.lastName,
user.password
]
)
}
const getByUsername = username => {
return connect()
.then(conn => {
conn.query(
`select id, username, firstName, lastName
from user
where username = ?`,
[username]
);
})
}
const create = user => {
return getByUsername(user.username)
.then(result => {
if (result.length > 0) {
throw new Error(`User "${user.username}" already exists`);
}
})
.then(() => connect())
.then(conn => insert(conn, user))
.then(result =>
({
id: result.insertId
}));
};
Controller file
const create = (req, res) => {
userService.create(req.body)
.then(result => {
res.status(200);
res.json(result);
})
.catch(err => {
res.status(500);
res.send('Error ' + err.message);
})
}
I tried to define lenght but I think this isnt the issue. I make the query with postman and i use mysql as database. I also tried to replace the result.length with username.length but it thorws "Error username is not defined"...