【问题标题】:Insert data with forEach() and Node.js使用 forEach() 和 Node.js 插入数据
【发布时间】:2020-05-14 08:31:12
【问题描述】:

我目前有这段代码,它通过textarea 标签输入数据。

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

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

</form>

在我的 .js 文件中,我有以下内容:

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);
    });
});

通过发送数据并通过控制台查看数据,表明一切顺利。

{ id_school: '34',tag: '20',email: 'example1@gmail.com' }
{ id_school: '34',tag: '20',email: 'example2@gmail.com' }

问题是当它保存在数据库中时,它只保存最后插入的电子邮件。

我尝试以这种方式保存电子邮件:

尝试将 .split 更改为 .match 并没有成功并以这种方式更改 .split 但没有。

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

我尝试将 .split 输入到 foreach 中,但无法将其正确保存在数据库中。

    _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);
    });

【问题讨论】:

    标签: mysql node.js express handlebars.js


    【解决方案1】:

    试试:

    db.query('INSERT INTO date set ?', { ...uStudent, email } );
    

    【讨论】:

    • 他尝试过这种方式:db.query('INSERT INTO date set ? and email = ?', {uStudent,email});db.query('INSERT INTO date set ?', {uStudent,email});db.query('INSERT INTO date set ? email = ?', [uStudent,email]); 但它给了我错误Error: ER_BAD_FIELD_ERROR: Unknown column 'uStudent' in 'field list'
    【解决方案2】:

    ?‍?也许你可以试试下面的这段代码?:

    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();
      });
    });
    

    ? 更新: 或者,如果您仍想在 foreach 中使用 query 可以使用下面的示例代码 ?:

    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);
          }
        });
      });
    });
    

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

      我知道这个问题已经得到解答,但我想提供一个替代解决方案。

      forEach 循环内,尝试在查询前使用await,如下所示:

      try {
         await db.query('INSERT INTO date set ?', uStudent);
      } catch (err) {
         console.error(err.message);
      }
      

      我相信这应该可以解决您的问题,因为 Node.js 是一个异步平台,这意味着它不会等待您的数据库查询完成(这很可能是您看到最后一封电子邮件添加两次的原因)。

      在查询前添加关键字await将强制执行线程在继续下一个查询之前解析。

      【讨论】:

        猜你喜欢
        • 2013-08-15
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 2018-04-06
        • 1970-01-01
        相关资源
        最近更新 更多