I have a problem where I have an array of objects like this:
[
{
department_id: '6256f8ae6f749617e8167416',
employee_id: '6253ca0c6f749618a8d022af',
employee_number: '1234'
},
{
department_id: '6256f8ae6f749617e8167416',
employee_id_id: '6253ca0c6f749618a8d022af',
employee_number: '1503'
}
]
and would like to use node.js and mysql to insert it into a database so I have got this script
Department.assignEmployeetoDepartment = (employees, result) => {
let employees_array = Object.values(rooms);
db.query(
`INSERT INTO department_employee (department_id, employee_id, employee_number) VALUES ?`,
[employees_array],
(err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("success: ", res);
result(null, res);
}
);
};
when I use the code above, I get
INSERT INTO department_employee (department_id, employee_id, employee_number) VALUES '[object Object]', '[object Object]'
which does not work for obvious reasons. I tried to stringify the object and I also tried to use a for loop to iterate over the employees array and it did not work as it says the headers were already sent.
How could I store the array (which can vary in length into the database? Thanks in advance
As per mysql- Escaping query values
Nested arrays are turned into grouped lists (for bulk inserts), eg [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
You probably want to map the values to array, you can't pass array of JSON object to query
db.query(
`INSERT INTO department_employee (department_id, employee_id, employee_number) VALUES ?`,
[employees_array.map(employee => [employee.department_id, employee.employee_id, employee.employee_number])],
(err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("success: ", res);
result(null, res);
}
);
};
The solution I'm suggesting for you will serve you safe if you make your data an array of arrays;
const employeesData = [
[
'6256f8ae6f749617e8167416',
'6253ca0c6f749618a8d022af',
'1234'
],
[
'6256f8ae6f749617e8167416',
'6253ca0c6f749618a8d022af',
'1503'
],
];
Next, prepare your query like this;
const sql = `INSERT INTO images (department_id, employee_id, employee_number) VALUES?`;
You're now ready to run your query liike below;
db
.query(sql, [employeesData])
.then(rows => {
res.status(200).json({
status: "success",
message:"Data inserted successfully"
});
})
.catch(err => {
res.status(500).json({
status: "error",
error: err.message
});
});
You can generate array of values to insert using array's map method like shown below,
employeesData = dataSourceArray.map ( (data) => {
return [
department_id,
employee_id,
employee_number
];
});
You can't insert an array in a table, an array IS a table
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.