2017-08-29 22 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

相关问题