findOne 查询的 Sequelize 循环

Sequelize loop of findOne queries

我有两个 tables A 和 B。场景是我 运行 循环中的数组在插入之前在 table A 上的 findOne 查询中使用这些条目进入 table B。即使 table A 中不存在数组中的一项,操作也应该失败。我现在的情况如下

var idList = [1,2,3,4,5];
for (i=0; i<idList.length; i++){
  await A.findOne({ where: { id : i }}).then((product) => {
    if(!product){
      notValidItem.push(i);
    }
  });
  if (notValidItem.length > 0){
    return res.status(400).send({ message : 'Invalid Operation' });
  }
  else{
    next();
    //going ahead with inserting into table B
  }
}

上述方法肯定有效...但是我们是否有更多的 lamda 或面向函数的实现而不是上面代码中的循环?在此先感谢您的帮助。

由于我的优势在于数组项和数据库中的项将是唯一的,因此以下方法对我有用

var idList = [1,2,3,4,5];
A.findAll({ where: { id : { [Op.in] : idList }}}).then((foundItems) => {
  foundItemsArray = foundItems.map((x) =>  x.id);
  diffence = idList.filter(x => !foundItemsArray.includes(x));
  if(diffence.length > 0){
    //failure here              
  }
  else{
    next();
  }
})

Promises 的一个解决方案是使用 Promise.all() 。如果这些 Promise 中的任何一个失败,您将收到一个错误。

try {
    let idList = [1,2,3,4,5];
    let promisesArray = [];
    for (i=0; i<idList.length; i++){
        promisesArray.push(A.findOne({ where: { id : i }}))
    }
    await Promise.all(promisesChangeMenuOrder);
    next();
} catch (error) {
    console.log(error) // don't console.log errors in production
    return res.status(400).send({ message : 'Invalid Operation' });
}

下一个解决方案是:

let rows = A.findAll({
    where: {
        id: [1,2,3,4,5]
    }
})

现在检查长度是否符合应有的长度,以及这些值是否为空。我认为这是更好的解决方案...