Search code examples
mysqlnode.jsexpresshandlebars.js

Insert data with forEach() and Node.js


I currently have this code, which enters data by a textarea tag.

textarea

<form class="" action="/registration/instudent/{{id_school}}/{{tag}}" method="post">

<textarea name="emails" ></textarea>            
<button class="btn btn-lg">Send</button>

</form>

In my .js file I have the following:

router.post('/instudent/:id_school/:tag', isLoggedIn, async (req,res) => {
  const { id_school, tag} = req.params;
  const { emails } = req.body;

  const uStudent = {
    id_school,
    tag
};

let _emails = emails.split(/\r?\n/);
    _emails.forEach(email => {

        // update uStudent email field
        uStudent.email = email;

        // insert the uStudent
        console.log(uStudent);
        db.query('INSERT INTO date set ?', uStudent);
    });
});

By sending the data and reviewing it by console, it indicates that everything is going well.

{ id_school: '34',tag: '20',email: '[email protected]' }
{ id_school: '34',tag: '20',email: '[email protected]' }

The problem is when it is saved in the database, it only saves the last email that was inserted.

emailr

What I try is to save the emails this way:

emailg

Try changing the .split to .match and it doesn't work out and change the .split in this way but nothing.

let _emails = emails.split('/\r?\n/');
let _emails = emails.split(/\n/);

I tried to enter the .split into foreach but I can't get it to save correctly in the database.

    _emails.forEach(email => {
        let _emails = emails.split(/\r?\n/);
        // update uStudent email field
        uStudent.email = email;

        // insert the uStudent
        console.log(uStudent);
        db.query('INSERT INTO date set ?', uStudent);
    });

Solution

  • 👨‍🏫 Maybe you can try this code below 👇:

    router.post('/instudent/:id_school/:tag', isLoggedIn, async (req,res) => {
      const { id_school, tag} = req.params;
      const { emails } = req.body;
    
      const newStudent = [];
    
      let _emails = emails.split(/\r?\n/);
        _emails.forEach(email => {
            newStudent.push([id_school, tag, email]);
        });
    
    
        var sql = "INSERT INTO date (id_school, tag, emails) VALUES ?";
    
        db.query(sql, [newStudent], function(err) {
          if (err) throw err;
          db.end();
      });
    });
    

    📤 Updated: Or if you still want to using query inside your foreach, than you can use an example code below 👇:

    router.post('/instudent/:id_school/:tag', isLoggedIn, async (req,res) => {
      const { id_school, tag} = req.params;
      const { emails } = req.body;
    
     emails.split(/\r?\n/).forEach(email => {
        const sql = 'INSERT INTO `date` (`id_school`, `tag`, `emails`) VALUES (?,?,?)';
        db.query(sql, [id_school, tag, email], (error, result) => {
          if(error) {
            console.log(error.message);
          }
        });
      });
    });
    

    I hope it can help you.