I have an array with objects. I want to import these into a sqlite3 database. I do this with a forEach loop. It works well. But I wonder why the objects are not imported in the order I put them into the database.
This is what I do
const comments = [
{post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"},
{post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"},
]
comments.forEach(c => {
sql = `INSERT INTO comments(post_id, comment, comment_author) VALUES (?,?,?)`
db.run(sql, [c.post_id, c.comment, c.comment_author], (err) => {
if (err) { console.log(err.message)};
});
});
If I now execute a select, I get the following pure order (take a look to post_id):
[
{id: 1, post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"},
{id: 2, post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"}
]
Question Why is this happening? And what can I do to change the behavior.
Expected result:
[
{id: 1, post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"},
{id: 2, post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"}
]
Note I Guess it has something to do with the async of javascript.
You are right with your guess: I Guess it has something to do with the async of javascript.!
let placeholders = comments.map((c) => '(?)').join(',');
let sql = 'INSERT INTO comments(post_id, comment, comment_author) VALUES ' + placeholders;
// output the INSERT statement
console.log(sql);
db.run(sql, [comments], (err, results, fields) => {
if (err) {
return console.error(err.message);
}
// get inserted rows
console.log('Row inserted:' + results.affectedRows);
});
// close the database connection
db.close();