【发布时间】:2020-02-29 12:40:32
【问题描述】:
我使用 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
})
我不知道应该如何使用后端或前端以及如何进行操作
【问题讨论】:
-
为此目的使用名为 Sequelize 的 ORM(对象关系映射)库。它将使查询和接收数据变得更加简单。
-
@HussainNawazLalee 你能帮我举个小例子吗
-
你必须添加一些样板文件,所以如果你已经在项目中走了很长一段路,我不推荐它,但如果你刚刚开始,你可以开始使用这个库。在您的项目中设置了 sequelize 之后。假设您想
SELECT * FROM Products。 Sequelize 将定义Product模型,您只需调用Product.findAll(),它将以 JSON 格式返回所有产品。您还有一些有用的方法,例如incldue来获取related Tables as nested objects以及许多其他可以轻松使用 Node 的方法 -
对于当前的用例,我添加了一个答案,可以帮助您格式化数据
-
您的代码目前也容易受到 SQL 注入的攻击,因此我真的建议您重新审视构建查询的方式,如果在 prod 中使用这种方式。