,

Inserting Multiple Records into a Database with Node.js and Express.js: Chapter 13 Assignment

Posted by

Node.js & Express.js Series | Chapter 13 | Assignment

Insert Multiple Records in Database

In this chapter, we will learn how to insert multiple records in a database using Node.js and Express.js.

Setting Up the Database

First, we need to create a database table to store the records. You can use any database system like MySQL, PostgreSQL, MongoDB, etc. For this example, let’s use MySQL.


CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) NOT NULL
);
  

Writing the Code

Now, let’s write the code to insert multiple records into the database using Node.js and Express.js.


const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'mydb'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to the database');
  
  const records = [
    { name: 'John Doe', email: 'john@example.com' },
    { name: 'Jane Smith', email: 'jane@example.com' },
    { name: 'Bob Johnson', email: 'bob@example.com' }
  ];

  const sql = 'INSERT INTO users (name, email) VALUES ?';

  connection.query(sql, [records.map(record => [record.name, record.email])], (err, result) => {
    if (err) throw err;
    console.log('Records inserted: ' + result.affectedRows);
  });
});
  

Conclusion

By following the above code, you can easily insert multiple records into a database using Node.js and Express.js. Feel free to modify the code according to your database system and requirements.