I am trying to INSERT multiple rows in MySQL, but I am getting the following error:
TypeError: argument callback must be a function when provided
When I INSERT one row it works perfectly.
Here is my code:
const createUserWorkouts = async (id, startDate) => {
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() days);
result = result.toJSON().slice(0, 19).replace("T", " ");
return result;
}
const newDate = addDays(startDate, 1);
console.log("newDate", newDate);
return new Promise((resolve, reject) => {
pool.query(
`
INSERT user_workouts
SET workout_id = ?, scheduled_at = ?, user_id = ?, program_enrollment_id = ?
`,
[1, newDate, id, 1],
[2, newDate, id, 1],
(error, elements) => {
if (error) {
return reject(error);
}
return resolve(elements);
}
);
});
};
I am not sure what is causing this issue.
I have also tried:
[[1, newDate, id, 1],
[2, newDate, id, 1],]
But I am still getting the same error.
CodePudding user response:
My mistake, I have just realised I am trying to use MySQL UPDATE syntax instead of INSERT.
This is how the correct query should look:
const createUserWorkouts = async (id, startDate) => {
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() days);
result = result.toJSON().slice(0, 19).replace("T", " ");
return result;
}
const newDate = addDays(startDate, 1);
console.log("newDate", newDate);
return new Promise((resolve, reject) => {
pool.query(
`
INSERT INTO user_workouts (workout_id, scheduled_at, user_id,
program_enrollment_id)
VALUES (?, ?, ?, ?)
`,
[[1, newDate, id, 1],
[2, newDate, id, 1],]
(error, elements) => {
if (error) {
return reject(error);
}
return resolve(elements);
}
);
});
};
Thank you to everyone who tried to help me.
CodePudding user response:
If you want to execute multiple queries manually, you could just enable multiplestatment parameter in your connection
EXAMPLE
var connection = mysql.createConnection({multipleStatements: true});
after that you could now type two set of queries in your query
SIMILAR TO THIS
connection.query('SELECT * FROM table1 WHERE id = ?; SELECT * FROM table2 WHERE id = ?', [1,2], and so on......);
However, if you are expecting a changing number of data to be queried in different instances, might as well create a looping statement as well depending on the length of array you have so that you would not code it manually.