【问题标题】:How can i push value to an array in a mysql query in nodeJS?如何在nodeJS的mysql查询中将值推送到数组?
【发布时间】:2021-11-08 04:27:36
【问题描述】:

我正在尝试将值推送到错误数组中,具体取决于查询的结果。

我尝试了几种方法,直接从箭头函数定义一个变量,返回记录的数量,但正如我所见,查询箭头函数不操纵变量。

如何在条件语句中使用返回的记录数?

const userExistence = "SELECT COUNT(*) AS countEmail FROM users WHERE Email = ?";
mysql.db.query(userExistence, [email], (err, result) => {
  if (result[0].countEmail !== 0) {
    errors.push({ msg: 'Account with this email address already exists' });
  }
        console.log(result[0].countEmail);
  console.log(err);
  res.end();
});

【问题讨论】:

  • 您需要知道 mysql.db.query.... 是异步函数,请将您的代码粘贴到问题中,以便我为您提供帮助。
  • 我想,是这样的,我粘贴了查询的sn-p。

标签: mysql node.js arrays express


【解决方案1】:

您必须在查询的回调函数中计算错误数组长度,因为查询函数是一个异步函数。

检查下面的代码:

const userExistence = "SELECT COUNT(*) AS countEmail FROM users WHERE Email = ?";
mysql.db.query(userExistence, [email], (err, result) => {
  if (result[0].countEmail !== 0) {
    errors.push({ msg: 'Account with this email address already exists' });
  }

  // Add your condition here.
  if(errors.length > 0) {
  }
  else {
  }

  console.log(result[0].countEmail);
  console.log(err);
  res.end();

});

【讨论】:

  • 谢谢,它正在工作,但是如果需要更多验证,有什么方法可以实现布尔变量或任何东西,以便稍后验证?还是只能在查询函数中实现?
  • 这取决于你想要做什么样的验证。 @GaramvolgyiSoma
  • 在这种情况下,仅当当前电子邮件地址已经注册时,但如果我也想检查名称存在怎么办?我应该将它嵌入到其他查询中,例如“mysql.db.query(userExistence ...) => { mysql.db.query(nameExistence ...) => { if ( ...”?
猜你喜欢
  • 2014-02-03
  • 1970-01-01
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 2016-02-24
  • 2015-02-09
相关资源
最近更新 更多