2017-08-29 60 views
1

我必須查詢一組我希望嵌套的數據以使其更有意義。當使用OracleDB的框架ExpressJS查詢數據如下,如何使用帶有ExpressJS的NodeJS使用oracledb查詢來構建和獲取嵌套的JSON對象

oracledb.getConnection(getConnectAttr, function(err,connection){ 
    if(err){ 
     res.set('content-type','application/json'); 
     res.status(500).send(JSON.stringify({ 
     status:500, 
     message:"Error connection to DB", 
     detailed_message:err.message 
     })); 
     return; 
    } 
     connection.execute("select * from REGISTRATION_MASTER", {}, {outFormat : oracledb.OBJECT 
     },function(err, result){ 
     if(err){ 
      res.set('content-type','application/json'); 
     res.status(500).send(JSON.stringify({ 
     status:500, 
     message:"Error connection the REGISTRATION", 
     detailed_message:err.message 
     })); 
     } 
     else{ 
      res.contentType('application/json').status(200); 
      res.send(result.rows); 
     } 

     //Release the connection 
     connection.release(
      function(err){ 
      if(err){ 
       console.error(err.message); 
      } 
      else{ 
       console.log("GET/comments : connection released") 
      } 
      }); 
     }); 

    }); 

我用於查詢和查詢結果會是這樣,

[ 
    { 
     "REG_ID": 1, 
     "REG_TEXT": "User Name", 
     "REG_VALUE": null, 
     "REG_IS_REQUIRED": "true", 
     "REG_TYPE": "text" 
    }, 
    { 
     "REG_ID": 2, 
     "REG_TEXT": "Password", 
     "REG_VALUE": null, 
     "REG_IS_REQUIRED": "true", 
     "REG_TYPE": "password" 
    }, 
    { 
     "REG_ID": 3, 
     "REG_TEXT": "First Name", 
     "REG_VALUE": null, 
     "REG_IS_REQUIRED": "true", 
     "REG_TYPE": "text" 
    } 
] 

我確實需要通過這樣的查詢,以形成一個JSON輸出應該像

{ 
    "REG_FIELDS": [{ 
    "REG_ID": 1, "REG_TEXT": "User Name", "REG_VALUE": "", "REG_IS_REQUIRED": "true", 
    "REG_TYPE": "text" 
    }, { 
    "REG_ID": 2, "REG_TEXT": "Password", "REG_VALUE": "", 
    "REG_IS_REQUIRED": "true", "REG_TYPE": "password" 
    }, { 
    "REG_ID": 3, "REG_TEXT": "First Name", 
    "REG_VALUE": "", "REG_IS_REQUIRED": "true", "REG_TYPE": "text" 
    }, ], 
    "MAINHEADING": "CONSUMER SIGNUP", 
    "SUBHEADER": "ACCOUNT - CONSUMER - SIGN UP", 
    "IS_ACTIVE": "TRUE" 
}; 

我正在尋找這樣的輸出與嵌套值。我的要求將會有更多的嵌套值。我正在尋找一個起點。

我也嘗試在ExpressJS中使用ORM,但是在使用ExpressJS和Oracle時各有其缺點。謝謝。

回答

2

您可以執行多個查詢,然後使用結果構建發送出的更復雜的數據結構。看看這個:https://jsao.io/2015/07/relational-to-json-with-node-js/

此外,請注意,你不應該發送數據庫錯誤到客戶端。這可以讓你開啓SQL注入,因爲它讓人們可以更多地瞭解你的數據庫。向客戶端發送一條通用消息並記錄實際的錯誤,以便調試它。

我很好奇,你試過什麼樣的ORM,有什麼缺點?

+0

我會仔細研究一下。看起來它給了我我正在尋找的東西。我idod看的ORM是Sworm(https://github.com/featurist/sworm),Typeorm(https://github.com/typeorm/typeorm) – Joseph

相關問題