Node.js如何将Postgresql查询结果的行转换为JSON数组?

时间:2018-08-25 12:54:28

标签: json node.js postgresql

我从postgreSQL数据库中获得了以下查询结果,然后我想将应该包含的部分发送给客户端。我需要响应为json格式,所以请您告诉我如何将查询结果:转换为json数组?

Result {
      command: 'SELECT',
      rowCount: 1,
      oid: NaN,
      rows:
       [ anonymous {
           uid: 23,
           name: 'Test Human',
           email: 'test@example.com',
           password: 'test',
           created: 2018-08-24T09:44:19.659Z,
           terminited: null } 
         anonymous {
           uid: 12,
           name: 'Test Animal',
           email: 'ani@example.com',
           password: 'hello',
           created: 2018-08-24T09:44:19.659Z,
           terminited: null }
      ],
      fields:
       ...
       _parsers:
       [ [Function: parseInteger],
         [Function: noParse],
         [Function: noParse],
         [Function: noParse],
         [Function: parseDate],
         [Function: parseDate] ],
      RowCtor: [Function: anonymous],
      rowAsArray: false,
      _getTypeParser: [Function: bound ] }

Node.js代码:

// router for get friends  information
router.get("/getfriends", (req, res) => {

   const uid = req.query.uid;
   pool.connect((err, client, done) => {
    if (err) throw err;
    const fetchRow = async() =>{
       await client.query('SELECT * FROM friends where follower = $1 ORDER by id ASC', [uid], (err, result) => {
         done()
         if(err){
           console.log(err.stack)
           res.status(400).json(err)
         } else {
           /*here I want to response rows only with JSON format, but result.rows doesn't realise that...*/
           console.log(result.rows)
           res.status(200).json(result.rows)
        }
      })
    }
    fetchRow()
   })
})

0 个答案:

没有答案