简体   繁体   English

findOne 查询的 Sequelize 循环

[英]Sequelize loop of findOne queries

I have two tables A and B. The scenario is that I run an array over a loop to use those entries in a findOne query on table A before inserting into table B. Even if one item from the array does not exist in table A the operation should fail.我有两个表 A 和 B。场景是我在循环上运行一个数组,以在插入表 B 之前在表 A 上的 findOne 查询中使用这些条目。即使数组中的一个项目在表 A 中不存在操作应该失败。 What I have now is as follows我现在拥有的如下

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

The above method works for sure... but do we have a more lamda or a function oriented implementation instead of the loop in the above code?上述方法肯定有效......但我们是否有更多 lamda 或 function 面向实现,而不是上述代码中的循环? Thanks in advance for any help.提前感谢您的帮助。

Since ive got an advantage that the array items and items from database are going to be unique the following method worked for me由于我有一个优势,即数据库中的数组项和项将是唯一的,因此以下方法对我有用

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

One solution with Promises would be to use Promise.all().使用 Promises 的一种解决方案是使用 Promise.all()。 If any of those Promises fail, you'll get an Error.如果其中任何一个 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' });
}

Next solution would be:下一个解决方案是:

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

And now check if length is what it should be and if non of those values is null.现在检查长度是否应该是,如果这些值不是 null。 This is much better solution I think...我认为这是更好的解决方案......

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

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