【问题标题】:Restful API with NodeJs and Mysql situation with "returns" object带有 NodeJs 的 Restful API 和带有“返回”对象的 Mysql 情况
【发布时间】:2018-11-21 02:59:28
【问题描述】:

我正在使用 NodeJs 和 Mysql 构建一个 Restful API,我正在尝试使用内部联接将结果从表中返回,但现在我返回整个“返回”对象,并且我想返回里面的数组像一个简单的 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
            });
        }
    });
});

【问题讨论】:

  • 你有没有尝试过任何方法来达到你想要的结果?
  • 嗨!我试图创建一个 javascript 对象并用这个查询填充它,但我没有成功。我看到了一个名为 sequelize 的库,但我认为如果我使用它,我将不得不创建一个完整的 ORM,甚至通过加入这个库而不是 sql 查询来获得结果。

标签: arrays node.js rest api


【解决方案1】:

有人回答了巴西的堆栈溢出社区,它按我的需要工作: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

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 2018-11-08
    • 2023-02-10
    • 1970-01-01
    • 2016-09-21
    • 2015-10-31
    • 2018-03-08
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多