Reputation: 539
I am in process of learning expressJS with NodeJS.
I am trying to insert multiple rows into mySQL table. Since the bulk insert query requires data like
[["a",1], ["b",2], ["c",3]]
How can I transform my array of objects to such form? Here is my JSON post data
[
{
"productID" : 1,
"stock": -3
},
{
"productID" : 1,
"stock": 5
}
]
How to tranform such JSON object into the multidimensional array?
[[1,-3],[1,5]]
Here is what I have tried so far.
let promises = []
req.body.map((n) => {
promises.push(new Promise(resolve => {
let { productID, stock } = n
let values = {
PRODUCT_ID: productID,
STOCK: stock
}
let sql = 'INSERT INTO product_stock_history SET ?'
db.connection.query(sql, values, (err, results) => {
if (err) {
console.log("Failed to add stocks record: " + err)
res.sendStatus(500)
return
} else {
res.send("Stock record has been added")
}
})
}))
})
The above code is working, but in the end I have error with the mySQL syntax which I believe something to do with the promise. I am not familiar with the promise :)
Error: Can't set headers after they are sent.
So what i want to achieve is just the mapping without Promise.
thanks
Upvotes: 0
Views: 196
Reputation: 35222
You could pass Object.values
as parameter to map
like this:
const input = [
{
"productID" : 1,
"stock": -3
},
{
"productID" : 1,
"stock": 5
}
]
const output = input.map(Object.values)
console.log(output)
Upvotes: 3