Tim Nuwin
Tim Nuwin

Reputation: 2887

Best practices for MySQL queries in NodeJS

I'm pretty new to nodeJS, and what's the best way to implement SQL queries..

When I'm doing a mysql insert in NodeJS I need to query to see if the value exists, then I need to do an additional query to grab the max value of 1 field.

Everything has call-backs, and relies on one query to execute before moving on to the next. This is getting pretty messy, especially because I have to pass all the callbacks in the functions.

I'm considering creating stored procedures to keep the logic cleaner..

this.get = function(data, callback, getMaxOrder, parentScope){
    var val = db.query('select * from my_table where ?', data, function(err, result) {
        if (err) throw err;

        callback(data, result, getMaxOrder, parentScope);
    });
}

this.getMaxOrder = function(data, callback, parentScope){
    var val = db.query('select max(`order`) as maxOrder from my_table where some_attr = ?', [data.some_attr], function(err, result) {
        if (err) throw err;

        callback(data, result, parentScope);
    });
}

this.parentInsert = function(data, callback){
    console.log("call parent insert..");
    db.config.queryFormat = db.config.defaultQueryFormat;
    db.query('insert into cards SET ?', data, function(err, result) {
        if (err) throw err;
        //callback(result);
    });     
}

this.insert = function(data, callback){
    //get all names w/ the same board id..

    var getResults = function(data, results, getMaxOrder, parentScope){
        if(results.length == 0){
            console.log("incremenet the order..");
            //by getting... max order..

            var maxOrderCallback = function (data, results, parentScope){
                var order = results[0].maxOrder + 1;
                //now update...                 


                var newData = {order: order, name: data.name, boardId: data.boardId, userId: data.userId};
                parentScope(newData);
            }



            getMaxOrder(data, maxOrderCallback, parentScope);
        }else{
            //throw "Name for card in the board already taken!";
        }
    }

    this.get(data, getResults, this.getMaxOrder, this.parentInsert);
 }

Upvotes: 1

Views: 5289

Answers (1)

Travis Webb
Travis Webb

Reputation: 15018

Classic case of Callback Hell. See if your mysql driver supports Promises. If not, there are some query generators that do:

Upvotes: 2

Related Questions