Raggaer
Raggaer

Reputation: 3318

Node.js express MySQL check for success

Currently my function looks like this

module.exports.processForm = function(req, res) {
    req.assert('username', 'Username field is required').notEmpty();
    req.assert('password', 'Password field is required').notEmpty();
    if (req.validationErrors()) {
        res.render('login.html', {title: 'Login form', errors: req.validationErrors()});
    }
    db.query('SELECT name FROM users WHERE name = ? LIMIT 1', req.body.username, function(errs, data) {
        if (errs) {
            res.render('login.html', {title: 'Login form', errors: 'Wrong password / username'});
        }
    });  
}

Im trying to select field name from table users but that field doesnt exists so how can I check if the query was executed successfully? I tried something like

if (data.length === 0) {
    res.render('login.html', {title: 'Login form', errors: 'Wrong password / username'});
}

With no success, if I try to res.send(data) it looks like this []

Upvotes: 0

Views: 2558

Answers (1)

mscdex
mscdex

Reputation: 106696

Your errs parameter will be an Error object if there was some kind of database or connection-related issue (e.g. bad SQL syntax or some other serious error). For SELECT queries, if data.length is zero that means the query was successful but resulted in zero rows.

So your solution of checking data.length === 0 is correct, but you should also check for and handle the errs argument also.

Upvotes: 2

Related Questions