Search code examples
mysqlnode.jspassport.jsnode-mysql

How to select rows[0] while inserting in node-mysql?


I'm fairly new to nodejs and callbacks. Here is my problem, using passportJS's LocalStrategy and node-mysql :

exports.register = new LocalStrategy(strategyOptionsRegister, function(req, username, password, done) {

    //get data from the request
    var data = {
        username: username,
        email: req.body.email,
        password: password
    };
    console.log('data : ', data);

    //Hash passwords
    bcrypt.genSalt(10, function(err, salt) {
        if (err) return next(err);

        bcrypt.hash(password, salt, null, function(err, hash) {
            // Store hash in your password DB.
            if (err) return next(err);

            data.password = hash;

            //insertion 
            connection.query('INSERT INTO USERS SET ?', data, function(err, rows) {
                if (err) {
                    console.log(err);
                    return next("Mysql error, check your query");
                }
                return done(null, rows[0]);
            });
        });
    });
});

I'm trying to return rows[0] containing all the data, but i don't know how should i implement the SELECT command ? Is it before or after the callback for the insertion ? For the moment, rows[0] is naturally undefined.


Solution

  • Here is my solution :

    exports.register = new LocalStrategy(strategyOptionsRegister, function(req, username, password, done) {
    
        //get data from the request
        var data = {
            username: username,
            email: req.body.email,
            password: password
        };
    
        //Hash passwords
        bcrypt.genSalt(10, function(err, salt) {
            if (err) {
                return done(err);
            }
    
            // Store hash in your password DB.
            bcrypt.hash(password, salt, null, function(err, hash) {
                if (err) {
                    return done(err);
                }
    
                data.password = hash;
    
                //insertion 
                connection.query('INSERT INTO USERS SET ?', data, function(err, rows) {
                    if (err) {
                        return done(null, false, {
                            message: 'Mysql error, check your query !'
                        });
                    }
                    // to return all the info in rows[0]
                    connection.query('SELECT * FROM USERS WHERE email = ?', data.email, function(err, rows) {
                        if (err) {
                            return done(null, false, {
                                message: 'Email not found !'
                            });
                        }
                        return done(null, rows[0]);
                    });
                });
            });
        });
    });