I'm pretty new to nodeJS, and what's the best way to implement SQL queries..
我是nodeJS的新手,以及实现SQL查询的最佳方法是什么。
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.
当我在NodeJS中进行mysql插入时,我需要查询该值是否存在,然后我需要进行额外的查询以获取1字段的最大值。
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);
}
1 个解决方案
#1
2
Classic case of Callback Hell. See if your mysql driver supports Promises. If not, there are some query generators that do:
Callback Hell的经典案例。看看你的mysql驱动程序是否支持Promises。如果没有,有一些查询生成器可以:
#1
2
Classic case of Callback Hell. See if your mysql driver supports Promises. If not, there are some query generators that do:
Callback Hell的经典案例。看看你的mysql驱动程序是否支持Promises。如果没有,有一些查询生成器可以: