首页 > 解决方案 > 如何从 findOne 函数 MySQL 返回布尔值

问题描述

我想将结果findOne用作if语句的条件。我无法返回,true或者false,我看到它的async功能有所不同,但尽管多次尝试都没有奏效。

控制器.js

  // Find a single User with a sub
exports.findOne = (req, res) => {
const sub = req.params.sub;

User.findOne({sub})
  .then(data => {
res.send(data);
  })
  .catch(err => {
res.status(500).send({
message: "Error retrieving User with sub=" +sub
});
  });
};

前端:

//INFO SAVE AND UPDATE CONDITION

async function exist() {
let x = await InfoDataService.get(data.sub)
console.log(x);
if (x === null) {

return true;

}
return false;
}

if ( exist() ) {
    InfoDataService.create(data)
      .then((response) => {
        console.log('create', response.data);
        setInfo({
          id: response.data.id,
          sub: response.data.sub,
          email: response.data.email,
          firstname: response.data.firstname,
          lastname: response.data.lastname
        });
      })
      
  } else {
    InfoDataService.update(sub, data)
      .then((response) => {
                
        console.log(response.data);
      })
      .catch((e) => {
        console.error(e);
      });
  }
  };

标签: mysqlnode.jsasynchronousasync-awaitsequelize.js

解决方案


您有 2 个选项可以做到这一点。两者只是相互补充。

// option 1 
if (x) {
    return true;
}
return false;

// OR
// option 2
if (!x) {
    return false;
}
return true;

推荐阅读