2013-04-28 63 views
4

我在發現Nodejs和node-mysql模塊。我有一個小問題。我找到的每個教程都解釋瞭如何在數據庫上進行選擇,但他們從不返回行,他們總是記錄它們,這對我的情況來說絕對沒有用處。用nodejs和node-mysql返回行

我有一個app.js文件:

// Get continents 
app.get("/continents", function(request, result) { 
    console.log("Continents : " + database.findAllContinents()); 
}); 

而且一個mysql.js文件:

exports.findAllContinents = function(connection) { 
    var connection = getConnection(); 
    connection.query('select id, code, name from Continent', function (err, rows, fields) { 
     if (err) { 
      console.log("Error in findAllContinents : " + err) 
     } 
     return JSON.stringify(rows); 
    }); 
    closeConnection(connection); 
}; 

我怎樣才能使函數返回行的app.js使用它們檔案?我真的不想在app.js文件中創建連接,我希望將DAO圖層分開。 你有什麼想法嗎?

另外,如果有人具有利用節點的MySQL代替ORM的優點/缺點的想法(sequelize,persistence.js ...)

由於

回答

14

query()是從異步函數您無法返回任何結果。因此,任何自己調用異步函數的函數(比如你的findAllContinents)都不能。

相反,你需要傳遞一個回調函數(也解釋here)當查詢完成將其稱之爲:

// app.js 
app.get("/continents", function(request, response) { 
    database.findAllContinents(function(err, results) { 
    if (err) 
     throw err; // or return an error message, or something 
    else 
     res.send(results); // as a demo, we'll send back the results to the client; 
         // if you pass an object to 'res.send()', it will send 
         // a JSON-response. 
    }); 
}); 

// mysql.js 
exports.findAllContinents = function(cb) { 
    var connection = getConnection(); 
    connection.query('select id, code, name from Continent', function (err, rows, fields) { 
    // close connection first 
    closeConnection(connection); 
    // done: call callback with results 
    cb(err, rows); 
    }); 
}; 

至於使用ORM,這真的取決於(不)用例。我會選擇一個ORM(我最喜歡的MySQL是patio),以防我的應用需要多個(複雜)模型,也許它們之間存在關聯。而且,ORM提供的抽象使得代碼更易於閱讀,並且通常允許更輕鬆地將應用程序移植到不同的數據庫。

+1

謝謝你做的工作:)。我更好地理解異步函數的概念。關於ORM,我來自PHP和Java,使用這些語言我自然會使用ORM,但事情似乎與Node.js「特殊」。我嘗試過Sequelize,並且有很多缺失的功能(例如像外鍵約束) – c4k 2013-04-28 15:23:02