首页 > 解决方案 > 如何使用node js和MySql以数组格式从数据库中获取数据

问题描述

我使用 node.js 作为服务器语言,使用 Mysql 作为数据库,所以我正在运行查询并从数据库中获取数据,但是以这样的格式显示

  [ BinaryRow { name: 'Dheeraj', amount: '77.0000' },
    BinaryRow { name: 'Raju', amount: '255.0000' } ]

我想要的是

    ['Dheeraj', 77.0000],
    ['Raju', 66255.000030],

这就是我在后端(node.js)中所做的:

我的模型:

static getChartData(phoneNo, userType) {

        let sql = 'select businessname as name,sum(billamt) amount from cashbackdispdets where consphoneno =' + phoneNo + ' group by  businessid order by tstime desc limit 10'
        return db.execute(sql, [phoneNo]);

我的控制器:

exports.getColumnChart = function(req, res) {
    const phoneNo = req.body.userId
    const userType = req.body.userType
    console.log(phoneNo)
    dashboardModule.getChartData(phoneNo, userType)
        .then(([rows]) => {
            if (rows.length > 0) {
                console.log(rows)
                return res.json(rows)
            } else {
                console.log("error")
                return res.status(404).json({ error: 'Phone No. already taken' })
            }
        })
    .catch((error) => {
        console.log(error)
        return res.status(404).json({ error: 'Something went wrong !!' })
    })
}

我将这些数据发送到Ui,当我收到它时,UI 它是数组内的对象形式,这不是我想要的所需数据类型

axios().post('/api/v1/Dashboard/DashboardColumnChart',this.form)
  .then(res=>{
    console.log(res.data)
    debugger
  this.chartData= res.data
       })

浏览器上的上述代码控制台如这个

我不知道应该用后端还是前端来做,以及如何做

标签: mysqlnode.jsvuejs2

解决方案


如果您想更改它,Nodejs 会向您发送 JSON 响应。最好在前端框架中更改或操作它。但是,如果您想按照您的要求在后端更改它,请确保这些行采用您想要接收的格式。

 let data = [ 
        { "name": "Dheeraj", "amount": "77.0000" }, 
        { "name": "Raju", "amount": "255.0000" } 
    ]
    // empty array to store the data
    let testData = [];
    data.forEach(element => {
          testData.push(element.name)
    });

推荐阅读