具有NodeJs和Mysql情况的Restful API与"返回"宾语

时间:2018-06-11 19:35:04

标签: arrays node.js rest api

我正在使用NodeJs和Mysql构建Restful API,并且我尝试使用内部联接将结果返回到表,但是现在我返回整个"返回&#34 ;对象和我想在数组内部返回数组,就像一个简单的json对象返回一个noSql数据库。

当前

[
    {
        coluna1: 'AAAAA',
        coluna2: 'XXXXX'
    },{
        coluna1: 'AAAAA',
        coluna2: 'YYYYY'
    },{
        coluna1: 'BBBBB',
        coluna2: 'ZZZZZ'
    },
]

所需

[
    {
        coluna1: 'AAAAA',
        outra_arary: [
            {
                coluna2:  'XXXXX'
            },{
                coluna2:  'YYYYY'
            }
        ]
    },{
        coluna1: 'BBBBB',
        outra_arary: [
            {
                coluna2:  'ZZZZZ'
            }
        ]
    }
]

这是我如何构建我的方法的一个例子:

router.get('/', (req, res, next) => {
    res.locals.connection.query(`select *
                                   from tabela1
                             inner join tabela2
                                on tabela1.id = tabela2.id;`, (error, results, fields) => {
        if (error) {
            res.send({
                "status" : 500,
                "error" : error,
                "response" : null
            });
        } else {
            res.send({
                "status" : 200,
                "error" : null,
                "response" : results
            });
        }
    });
});

1 个答案:

答案 0 :(得分:0)

有人回答了巴西社区的堆栈溢出问题,它可以按照我的需要运行:https://pt.stackoverflow.com/questions/306134/restful-api-com-nodejs-e-mysql-com-multiplas-colunas-quero-retornar-json-em-nív

// Response from Mysql
const resultados = [
  {
      coluna1: 'AAAAA',
      coluna2: 'XXXXX'
  },{
      coluna1: 'AAAAA',
      coluna2: 'YYYYY'
  },{
      coluna1: 'BBBBB',
      coluna2: 'ZZZZZ'
  },
]

// Function that returns an array "other_array" that contains many objects with the data of the second column.
function retornaColuna(coluna) {
  const colunaFiltrada = new Array()
  resultados.forEach(valor => {
    if(valor.coluna1 == coluna)
      colunaFiltrada.push({ coluna2: valor.coluna2 })
  })
  return colunaFiltrada
}

// Create the expected structure
let resposta = new Array()
resultados.forEach(valor => {
  resposta.push({ coluna1: valor.coluna1, outra_array: retornaColuna(valor.coluna1) })
})

// Remove the duplicated columns 
resposta = resposta.filter((a) => !this[JSON.stringify(a)] && (this[JSON.stringify(a)] = true))

console.log(resposta) // It will return the expected