Search code examples
mysqlnode.jsforeach

Insert email with unique id node js


How am I working with nodejs, mysql, forEach trying to save the email in my DB with a unique id, using the textarea tag, based on this question

Insert multiple email to mysql using single textarea

For-each over an array in JavaScript

javascript split on non-alphanumeric an keep delimiters at start

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

<textarea name="email" ></textarea>            
<button class="btn btn-lg">Save</button>

</form>

Using the example in PHP base, in my example.js file I have this code, try to save all three variables.

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

  var uStudent = {
    id_school,
    mat,
    grade,
    email
}

Object.keys(uStudent).forEach(function (key){
    console.log(uStudent[key]);
    db.query('INSERT INTO date set ?', uStudent);
});
  //res.redirect('/');
});

When saving to my database, incorrectly insert the texts.

In my database it inserts the data this way:

enter image description here

Any guide to see what I am doing wrong and that every email in the textarea tag gets a unique id?

Correct form:

enter image description here


Solution

  • I can't find where in the code you are setting the email value to be save.

    there are some question here:

    1. You are looping base on your object keys(is this the correct behavior)?
    2. where did you update the uStudent to update its email?

    I think you should loop based on splitted email:

    router.post('/instudent/:id_school/:mat/:grade', isLoggedIn, async (req,res) => {
        const { id_school, mat, grade } = req.params;
        const { emails } = req.body;
    
        const uStudent = {
            id_school,
            mat,
            grade
        };
    
        // loop base on email
        let _emails = emails.split(/\r?\n/);
        _emails.forEach(email => {
    
            // update uStudent email field
            uStudent.email = email;
    
            // insert the uStudent
            db.query('INSERT INTO date set ?', uStudent);
        });
    });