Home > Enterprise >  Sequelize loop of findOne queries
Sequelize loop of findOne queries

Time:12-13

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. 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? Thanks in advance for any help.

CodePudding user response:

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

CodePudding user response:

One solution with Promises would be to use Promise.all() . If any of those Promises fail, you'll get an Error.

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. This is much better solution I think...

  • Related