NodeJS -> Error Cannot read property 'length' of undefined

Dariun :

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"...

Gokulakannan T :

The result might be undefined there. Because we don't return proper query results. That why we getting error.

Solution:

const getByUsername = username => {
    return new Promise((resolve, reject) => {
        connect()
            .then(conn => {
                conn.query( 
                    `select id, username, firstName, lastName
                    from user
                    where username = ?`,
                    [username],
                    function(err, results) {
                        if (err) {
                            return reject(err);
                        }
                        return resolve(results)
                    }  
                );
            })
    });
}

Explanation:

As per mysql2 documentation, the conn.query will not return the results. The conn.query method has a third argument which is a callback method. Here we can get the SQL query error and query results.

By the use of javascript Promise API, we can decide to reject or resolve based upon the SQL query result.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8509&siteId=1