繁体   English   中英

findOne 查询的 Sequelize 循环

[英]Sequelize loop of findOne queries

我有两个表 A 和 B。场景是我在循环上运行一个数组,以在插入表 B 之前在表 A 上的 findOne 查询中使用这些条目。即使数组中的一个项目在表 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 或 function 面向实现,而不是上述代码中的循环? 提前感谢您的帮助。

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

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

现在检查长度是否应该是,如果这些值不是 null。 我认为这是更好的解决方案......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM